home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 May / maximum-cd-2009-05.iso / DiscContents / Firefox Setup 3.0.6.exe / nonlocalized / components / nsUpdateService.js < prev    next >
Encoding:
Text File  |  2009-01-19  |  110.2 KB  |  3,335 lines

  1. //@line 44 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  2.  
  3. const PREF_APP_UPDATE_ENABLED             = "app.update.enabled";
  4. const PREF_APP_UPDATE_AUTO                = "app.update.auto";
  5. const PREF_APP_UPDATE_MODE                = "app.update.mode";
  6. const PREF_APP_UPDATE_SILENT              = "app.update.silent";
  7. const PREF_APP_UPDATE_INTERVAL            = "app.update.interval";
  8. const PREF_APP_UPDATE_TIMER               = "app.update.timer";
  9. const PREF_APP_UPDATE_IDLETIME            = "app.update.idletime";
  10. const PREF_APP_UPDATE_PROMPTWAITTIME      = "app.update.promptWaitTime";
  11. const PREF_APP_UPDATE_LOG_BRANCH          = "app.update.log.";
  12. const PREF_APP_UPDATE_URL                 = "app.update.url";
  13. const PREF_APP_UPDATE_URL_OVERRIDE        = "app.update.url.override";
  14. const PREF_APP_UPDATE_URL_DETAILS         = "app.update.url.details";
  15. const PREF_APP_UPDATE_CHANNEL             = "app.update.channel";
  16. const PREF_APP_UPDATE_SHOW_INSTALLED_UI   = "app.update.showInstalledUI";
  17. const PREF_APP_UPDATE_LASTUPDATETIME_FMT  = "app.update.lastUpdateTime.%ID%";
  18. const PREF_GENERAL_USERAGENT_LOCALE       = "general.useragent.locale";
  19. const PREF_APP_UPDATE_INCOMPATIBLE_MODE   = "app.update.incompatible.mode";
  20. const PREF_UPDATE_NEVER_BRANCH            = "app.update.never.";
  21. const PREF_PARTNER_BRANCH                 = "app.partner.";
  22. const PREF_APP_DISTRIBUTION               = "distribution.id";
  23. const PREF_APP_DISTRIBUTION_VERSION       = "distribution.version";
  24.  
  25. const URI_UPDATE_PROMPT_DIALOG  = "chrome://mozapps/content/update/updates.xul";
  26. const URI_UPDATE_HISTORY_DIALOG = "chrome://mozapps/content/update/history.xul";
  27. const URI_BRAND_PROPERTIES      = "chrome://branding/locale/brand.properties";
  28. const URI_UPDATES_PROPERTIES    = "chrome://mozapps/locale/update/updates.properties";
  29. const URI_UPDATE_NS             = "http://www.mozilla.org/2005/app-update";
  30.  
  31. const KEY_GREDIR          = "GreD";
  32. const KEY_APPDIR          = "XCurProcD";
  33. //@line 76 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  34. const KEY_UPDROOT         = "UpdRootD";
  35. const KEY_UAPPDATA        = "UAppData";
  36. //@line 79 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  37.  
  38. const DIR_UPDATES         = "updates";
  39. const FILE_UPDATE_STATUS  = "update.status";
  40. const FILE_UPDATE_ARCHIVE = "update.mar";
  41. const FILE_UPDATE_LOG     = "update.log"
  42. const FILE_UPDATES_DB     = "updates.xml";
  43. const FILE_UPDATE_ACTIVE  = "active-update.xml";
  44. const FILE_PERMS_TEST     = "update.test";
  45. const FILE_LAST_LOG       = "last-update.log";
  46. const FILE_UPDATER_INI    = "updater.ini";
  47.  
  48. const MODE_RDONLY   = 0x01;
  49. const MODE_WRONLY   = 0x02;
  50. const MODE_CREATE   = 0x08;
  51. const MODE_APPEND   = 0x10;
  52. const MODE_TRUNCATE = 0x20;
  53.  
  54. const PERMS_FILE      = 0644;
  55. const PERMS_DIRECTORY = 0755;
  56.  
  57. const STATE_NONE            = "null";
  58. const STATE_DOWNLOADING     = "downloading";
  59. const STATE_PENDING         = "pending";
  60. const STATE_APPLYING        = "applying";
  61. const STATE_SUCCEEDED       = "succeeded";
  62. const STATE_DOWNLOAD_FAILED = "download-failed";
  63. const STATE_FAILED          = "failed";
  64.  
  65. // From updater/errors.h:
  66. const WRITE_ERROR = 7;
  67.  
  68. const DOWNLOAD_CHUNK_SIZE           = 300000; // bytes
  69. const DOWNLOAD_BACKGROUND_INTERVAL  = 600;    // seconds
  70. const DOWNLOAD_FOREGROUND_INTERVAL  = 0;
  71.  
  72. const TOOLKIT_ID              = "toolkit@mozilla.org";
  73.  
  74. const POST_UPDATE_CONTRACTID = "@mozilla.org/updates/post-update;1";
  75.  
  76. const nsIExtensionManager     = Components.interfaces.nsIExtensionManager;
  77. const nsILocalFile            = Components.interfaces.nsILocalFile;
  78. const nsIUpdateService        = Components.interfaces.nsIUpdateService;
  79. const nsIUpdateItem           = Components.interfaces.nsIUpdateItem;
  80. const nsIPrefLocalizedString  = Components.interfaces.nsIPrefLocalizedString;
  81. const nsIIncrementalDownload  = Components.interfaces.nsIIncrementalDownload;
  82. const nsIFileInputStream      = Components.interfaces.nsIFileInputStream;
  83. const nsIFileOutputStream     = Components.interfaces.nsIFileOutputStream;
  84. const nsICryptoHash           = Components.interfaces.nsICryptoHash;
  85. const nsIINIParserFactory     = Components.interfaces.nsIINIParserFactory;
  86.  
  87. const Node = Components.interfaces.nsIDOMNode;
  88.  
  89. var gApp        = null;
  90. var gPref       = null;
  91. var gABI        = null;
  92. var gOSVersion  = null;
  93. var gLocale     = null;
  94. var gConsole    = null;
  95. var gLogEnabled = { };
  96.  
  97. // shared code for suppressing bad cert dialogs
  98. //@line 40 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\shared\src\badCertHandler.js"
  99.  
  100. /**
  101.  * Only allow built-in certs for HTTPS connections.  See bug 340198.
  102.  */
  103. function checkCert(channel) {
  104.   if (!channel.originalURI.schemeIs("https"))  // bypass
  105.     return;
  106.  
  107.   const Ci = Components.interfaces;  
  108.   var cert =
  109.       channel.securityInfo.QueryInterface(Ci.nsISSLStatusProvider).
  110.       SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert;
  111.  
  112.   var issuer = cert.issuer;
  113.   while (issuer && !cert.equals(issuer)) {
  114.     cert = issuer;
  115.     issuer = cert.issuer;
  116.   }
  117.  
  118.   if (!issuer || issuer.tokenName != "Builtin Object Token")
  119.     throw "cert issuer is not built-in";
  120. }
  121.  
  122. /**
  123.  * This class implements nsIBadCertListener.  It's job is to prevent "bad cert"
  124.  * security dialogs from being shown to the user.  It is better to simply fail
  125.  * if the certificate is bad. See bug 304286.
  126.  */
  127. function BadCertHandler() {
  128. }
  129. BadCertHandler.prototype = {
  130.  
  131.   // nsIChannelEventSink
  132.   onChannelRedirect: function(oldChannel, newChannel, flags) {
  133.     // make sure the certificate of the old channel checks out before we follow
  134.     // a redirect from it.  See bug 340198.
  135.     checkCert(oldChannel);
  136.   },
  137.  
  138.   // Suppress any certificate errors
  139.   notifyCertProblem: function(socketInfo, status, targetSite) {
  140.     return true;
  141.   },
  142.  
  143.   // Suppress any ssl errors
  144.   notifySSLError: function(socketInfo, error, targetSite) {
  145.     return true;
  146.   },
  147.  
  148.   // nsIInterfaceRequestor
  149.   getInterface: function(iid) {
  150.     return this.QueryInterface(iid);
  151.   },
  152.  
  153.   // nsISupports
  154.   QueryInterface: function(iid) {
  155.     if (!iid.equals(Components.interfaces.nsIChannelEventSink) &&
  156.         !iid.equals(Components.interfaces.nsIBadCertListener2) &&
  157.         !iid.equals(Components.interfaces.nsISSLErrorListener) &&
  158.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  159.         !iid.equals(Components.interfaces.nsISupports))
  160.       throw Components.results.NS_ERROR_NO_INTERFACE;
  161.     return this;
  162.   }
  163. };
  164. //@line 141 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  165.  
  166. /**
  167.  * Logs a string to the error console.
  168.  * @param   string
  169.  *          The string to write to the error console..
  170.  */
  171. function LOG(module, string) {
  172.   if (module in gLogEnabled || "all" in gLogEnabled) {
  173.     dump("*** " + module + ": " + string + "\n");
  174.     gConsole.logStringMessage(string);
  175.   }
  176. }
  177.  
  178. /**
  179.  * Convert a string containing binary values to hex.
  180.  */
  181. function binaryToHex(input) {
  182.   var result = "";
  183.   for (var i = 0; i < input.length; ++i) {
  184.     var hex = input.charCodeAt(i).toString(16);
  185.     if (hex.length == 1)
  186.       hex = "0" + hex;
  187.     result += hex;
  188.   }
  189.   return result;
  190. }
  191.  
  192. /**
  193.  * Gets a File URL spec for a nsIFile
  194.  * @param   file
  195.  *          The file to get a file URL spec to
  196.  * @returns The file URL spec to the file
  197.  */
  198. function getURLSpecFromFile(file) {
  199.   var ioServ = Components.classes["@mozilla.org/network/io-service;1"]
  200.                          .getService(Components.interfaces.nsIIOService);
  201.   var fph = ioServ.getProtocolHandler("file")
  202.                   .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
  203.   return fph.getURLSpecFromFile(file);
  204. }
  205.  
  206. /**
  207.  * Gets the specified directory at the specified hierarchy under a
  208.  * Directory Service key.
  209.  * @param   key
  210.  *          The Directory Service Key to start from
  211.  * @param   pathArray
  212.  *          An array of path components to locate beneath the directory
  213.  *          specified by |key|
  214.  * @return  nsIFile object for the location specified. If the directory
  215.  *          requested does not exist, it is created, along with any
  216.  *          parent directories that need to be created.
  217.  */
  218. function getDir(key, pathArray) {
  219.   return getDirInternal(key, pathArray, true, false);
  220. }
  221.  
  222. /**
  223.  * Gets the specified directory at the specified hierarchy under a
  224.  * Directory Service key.
  225.  * @param   key
  226.  *          The Directory Service Key to start from
  227.  * @param   pathArray
  228.  *          An array of path components to locate beneath the directory
  229.  *          specified by |key|
  230.  * @return  nsIFile object for the location specified. If the directory
  231.  *          requested does not exist, it is NOT created.
  232.  */
  233. function getDirNoCreate(key, pathArray) {
  234.   return getDirInternal(key, pathArray, false, false);
  235. }
  236.  
  237. /**
  238.  * Gets the specified directory at the specified hierarchy under the
  239.  * update root directory.
  240.  * @param   pathArray
  241.  *          An array of path components to locate beneath the directory
  242.  *          specified by |key|
  243.  * @return  nsIFile object for the location specified. If the directory
  244.  *          requested does not exist, it is created, along with any
  245.  *          parent directories that need to be created.
  246.  */
  247. function getUpdateDir(pathArray) {
  248.   return getDirInternal(KEY_APPDIR, pathArray, true, true);
  249. }
  250.  
  251. /**
  252.  * Gets the specified directory at the specified hierarchy under a
  253.  * Directory Service key.
  254.  * @param   key
  255.  *          The Directory Service Key to start from
  256.  * @param   pathArray
  257.  *          An array of path components to locate beneath the directory
  258.  *          specified by |key|
  259.  * @param   shouldCreate
  260.  *          true if the directory hierarchy specified in |pathArray|
  261.  *          should be created if it does not exist,
  262.  *          false otherwise.
  263.  * @param   update
  264.  *          true if finding the update directory,
  265.  *          false otherwise.
  266.  * @return  nsIFile object for the location specified.
  267.  */
  268. function getDirInternal(key, pathArray, shouldCreate, update) {
  269.   var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"]
  270.                               .getService(Components.interfaces.nsIProperties);
  271.   var dir = fileLocator.get(key, Components.interfaces.nsIFile);
  272. //@line 249 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  273.   if (update) {
  274.     try {
  275.       dir = fileLocator.get(KEY_UPDROOT, Components.interfaces.nsIFile);
  276.     } catch (e) {
  277.     }
  278.   }
  279. //@line 256 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  280.   for (var i = 0; i < pathArray.length; ++i) {
  281.     dir.append(pathArray[i]);
  282.     if (shouldCreate && !dir.exists())
  283.       dir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  284.   }
  285.   return dir;
  286. }
  287.  
  288. /**
  289.  * Gets the file at the specified hierarchy under a Directory Service key.
  290.  * @param   key
  291.  *          The Directory Service Key to start from
  292.  * @param   pathArray
  293.  *          An array of path components to locate beneath the directory
  294.  *          specified by |key|. The last item in this array must be the
  295.  *          leaf name of a file.
  296.  * @return  nsIFile object for the file specified. The file is NOT created
  297.  *          if it does not exist, however all required directories along
  298.  *          the way are.
  299.  */
  300. function getFile(key, pathArray) {
  301.   var file = getDir(key, pathArray.slice(0, -1));
  302.   file.append(pathArray[pathArray.length - 1]);
  303.   return file;
  304. }
  305.  
  306. /**
  307.  * Gets the file at the specified hierarchy under the update root directory.
  308.  * @param   pathArray
  309.  *          An array of path components to locate beneath the directory
  310.  *          specified by |key|. The last item in this array must be the
  311.  *          leaf name of a file.
  312.  * @return  nsIFile object for the file specified. The file is NOT created
  313.  *          if it does not exist, however all required directories along
  314.  *          the way are.
  315.  */
  316. function getUpdateFile(pathArray) {
  317.   var file = getUpdateDir(pathArray.slice(0, -1));
  318.   file.append(pathArray[pathArray.length - 1]);
  319.   return file;
  320. }
  321.  
  322. /**
  323.  * Closes a Safe Output Stream
  324.  * @param   fos
  325.  *          The Safe Output Stream to close
  326.  */
  327. function closeSafeOutputStream(fos) {
  328.   if (fos instanceof Components.interfaces.nsISafeOutputStream) {
  329.     try {
  330.       fos.finish();
  331.     }
  332.     catch (e) {
  333.       fos.close();
  334.     }
  335.   }
  336.   else
  337.     fos.close();
  338. }
  339.  
  340. /**
  341.  * Returns human readable status text from the updates.properties bundle
  342.  * based on an error code
  343.  * @param   code
  344.  *          The error code to look up human readable status text for
  345.  * @param   defaultCode
  346.  *          The default code to look up should human readable status text
  347.  *          not exist for |code|
  348.  * @returns A human readable status text string
  349.  */
  350. function getStatusTextFromCode(code, defaultCode) {
  351.   var sbs =
  352.       Components.classes["@mozilla.org/intl/stringbundle;1"].
  353.       getService(Components.interfaces.nsIStringBundleService);
  354.   var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  355.   var reason = updateBundle.GetStringFromName("checker_error-" + defaultCode);
  356.   try {
  357.     reason = updateBundle.GetStringFromName("checker_error-" + code);
  358.     LOG("General", "Transfer Error: " + reason + ", code: " + code);
  359.   }
  360.   catch (e) {
  361.     // Use the default reason
  362.     LOG("General", "Transfer Error: " + reason + ", code: " + defaultCode);
  363.   }
  364.   return reason;
  365. }
  366.  
  367. /**
  368.  * Get the Active Updates directory
  369.  * @param   key
  370.  *          The Directory Service Key (optional).
  371.  *          If used, don't search local appdata on Win32 and don't create dir.
  372.  * @returns The active updates directory, as a nsIFile object
  373.  */
  374. function getUpdatesDir(key) {
  375.   // Right now, we only support downloading one patch at a time, so we always
  376.   // use the same target directory.
  377.   var fileLocator =
  378.       Components.classes["@mozilla.org/file/directory_service;1"].
  379.       getService(Components.interfaces.nsIProperties);
  380.   var appDir;
  381.   if (key)
  382.     appDir = fileLocator.get(key, Components.interfaces.nsIFile);
  383.   else {
  384.     appDir = fileLocator.get(KEY_APPDIR, Components.interfaces.nsIFile);
  385. //@line 362 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  386.     try {
  387.       appDir = fileLocator.get(KEY_UPDROOT, Components.interfaces.nsIFile);
  388.     } catch (e) {
  389.     }
  390. //@line 367 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  391.   }
  392.   appDir.append(DIR_UPDATES);
  393.   appDir.append("0");
  394.   if (!appDir.exists() && !key)
  395.     appDir.create(nsILocalFile.DIRECTORY_TYPE, PERMS_DIRECTORY);
  396.   return appDir;
  397. }
  398.  
  399. /**
  400.  * Reads the update state from the update.status file in the specified
  401.  * directory.
  402.  * @param   dir
  403.  *          The dir to look for an update.status file in
  404.  * @returns The status value of the update.
  405.  */
  406. function readStatusFile(dir) {
  407.   var statusFile = dir.clone();
  408.   statusFile.append(FILE_UPDATE_STATUS);
  409.   LOG("General", "Reading Status File: " + statusFile.path);
  410.   return readStringFromFile(statusFile) || STATE_NONE;
  411. }
  412.  
  413. /**
  414.  * Writes the current update operation/state to a file in the patch
  415.  * directory, indicating to the patching system that operations need
  416.  * to be performed.
  417.  * @param   dir
  418.  *          The patch directory where the update.status file should be
  419.  *          written.
  420.  * @param   state
  421.  *          The state value to write.
  422.  */
  423. function writeStatusFile(dir, state) {
  424.   var statusFile = dir.clone();
  425.   statusFile.append(FILE_UPDATE_STATUS);
  426.   writeStringToFile(statusFile, state);
  427. }
  428.  
  429. /**
  430.  * Removes the Updates Directory
  431.  * @param   key
  432.  *          The Directory Service Key under which update directory resides
  433.  *          (optional).
  434.  */
  435. function cleanUpUpdatesDir(key) {
  436.   // Bail out if we don't have appropriate permissions
  437.   var updateDir;
  438.   try {
  439.     updateDir = getUpdatesDir(key);
  440.   }
  441.   catch (e) {
  442.     return;
  443.   }
  444.  
  445.   var e = updateDir.directoryEntries;
  446.   while (e.hasMoreElements()) {
  447.     var f = e.getNext().QueryInterface(Components.interfaces.nsIFile);
  448.     // Preserve the last update log file for debugging purposes
  449.     if (f.leafName == FILE_UPDATE_LOG) {
  450.       try {
  451.         var dir = f.parent.parent;
  452.         var logFile = dir.clone();
  453.         logFile.append(FILE_LAST_LOG);
  454.         if (logFile.exists())
  455.           logFile.remove(false);
  456.         f.copyTo(dir, FILE_LAST_LOG);
  457.       }
  458.       catch (e) {
  459.         LOG("General", "Failed to copy file: " + f.path);
  460.       }
  461.     }
  462.     // Now, recursively remove this file.  The recusive removal is really
  463.     // only needed on Mac OSX because this directory will contain a copy of
  464.     // updater.app, which is itself a directory.
  465.     try {
  466.       f.remove(true);
  467.     }
  468.     catch (e) {
  469.       LOG("General", "Failed to remove file: " + f.path);
  470.     }
  471.   }
  472.   try {
  473.     updateDir.remove(false);
  474.   } catch (e) {
  475.     LOG("General", "Failed to remove update directory: " + updateDir.path +
  476.         " - This is almost always bad. Exception = " + e);
  477.     throw e;
  478.   }
  479. }
  480.  
  481. /**
  482.  * Clean up updates list and the updates directory.
  483.  * @param   key
  484.  *          The Directory Service Key under which update directory resides
  485.  *          (optional).
  486.  */
  487. function cleanupActiveUpdate(key) {
  488.   // Move the update from the Active Update list into the Past Updates list.
  489.   var um =
  490.       Components.classes["@mozilla.org/updates/update-manager;1"].
  491.       getService(Components.interfaces.nsIUpdateManager);
  492.   um.activeUpdate = null;
  493.   um.saveUpdates();
  494.  
  495.   // Now trash the updates directory, since we're done with it
  496.   cleanUpUpdatesDir(key);
  497. }
  498.  
  499. /**
  500.  * Gets a preference value, handling the case where there is no default.
  501.  * @param   func
  502.  *          The name of the preference function to call, on nsIPrefBranch
  503.  * @param   preference
  504.  *          The name of the preference
  505.  * @param   defaultValue
  506.  *          The default value to return in the event the preference has
  507.  *          no setting
  508.  * @returns The value of the preference, or undefined if there was no
  509.  *          user or default value.
  510.  */
  511. function getPref(func, preference, defaultValue) {
  512.   try {
  513.     return gPref[func](preference);
  514.   }
  515.   catch (e) {
  516.   }
  517.   return defaultValue;
  518. }
  519.  
  520. /**
  521.  * Gets the locale specified by the 'Locale' key in the 'Installation' section
  522.  * of updater.ini if it is available. Otherwise the general.useragent.locale
  523.  * preference is used to get the locale. It's possible for this preference to
  524.  * be localized, so we have to do a little extra work here. Similar code
  525.  * exists in nsHttpHandler.cpp when building the UA string.
  526.  */
  527. function getLocale() {
  528.   if (gLocale)
  529.     return gLocale;
  530.  
  531.   try {
  532. //@line 512 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  533.     var updaterIni = getFile(KEY_GREDIR, [FILE_UPDATER_INI]);
  534. //@line 514 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  535.     var iniParser = Components.classes["@mozilla.org/xpcom/ini-parser-factory;1"]
  536.                               .getService(nsIINIParserFactory).createINIParser(updaterIni);
  537.     gLocale = iniParser.getString("Installation", "Locale");
  538.     LOG("General", "Getting Locale from File: " + updaterIni.path + " Locale: " + gLocale);
  539.     return gLocale;
  540.   } catch (e) {}
  541.  
  542.   try {
  543.     // Get the default branch
  544.     var prefs = Components.classes["@mozilla.org/preferences-service;1"]
  545.         .getService(Components.interfaces.nsIPrefService);
  546.     var defaultPrefs = prefs.getDefaultBranch(null);
  547.     gLocale = defaultPrefs.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  548.   } catch (e) {
  549.     gLocale = gPref.getCharPref(PREF_GENERAL_USERAGENT_LOCALE);
  550.   }
  551.  
  552.   return gLocale;
  553. }
  554.  
  555. /**
  556.  * Read the update channel from defaults only.  We do this to ensure that
  557.  * the channel is tightly coupled with the application and does not apply
  558.  * to other instances of the application that may use the same profile.
  559.  */
  560. function getUpdateChannel() {
  561.   var channel = "default";
  562.   var prefName;
  563.   var prefValue;
  564.  
  565.   var defaults =
  566.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  567.       getDefaultBranch(null);
  568.   try {
  569.     channel = defaults.getCharPref(PREF_APP_UPDATE_CHANNEL);
  570.   } catch (e) {
  571.     // use default when pref not found
  572.   }
  573.  
  574.   try {
  575.     var partners = gPref.getChildList(PREF_PARTNER_BRANCH, { });
  576.     if (partners.length) {
  577.       channel += "-cck";
  578.       partners.sort();
  579.  
  580.       for each (prefName in partners) {
  581.         prefValue = gPref.getCharPref(prefName);
  582.         channel += "-" + prefValue;
  583.       }
  584.     }
  585.   }
  586.   catch (e) {
  587.     Components.utils.reportError(e);
  588.   }
  589.  
  590.   return channel;
  591. }
  592.  
  593. /* Get the distribution pref values, from defaults only */
  594. function getDistributionPrefValue(aPrefName) {
  595.   var prefValue = "default";
  596.  
  597.   var defaults =
  598.       gPref.QueryInterface(Components.interfaces.nsIPrefService).
  599.       getDefaultBranch(null);
  600.   try {
  601.     prefValue = defaults.getCharPref(aPrefName);
  602.   } catch (e) {
  603.     // use default when pref not found
  604.   }
  605.  
  606.   return prefValue;
  607. }
  608.  
  609. /**
  610.  * An enumeration of items in a JS array.
  611.  * @constructor
  612.  */
  613. function ArrayEnumerator(aItems) {
  614.   this._index = 0;
  615.   if (aItems) {
  616.     for (var i = 0; i < aItems.length; ++i) {
  617.       if (!aItems[i])
  618.         aItems.splice(i, 1);
  619.     }
  620.   }
  621.   this._contents = aItems;
  622. }
  623.  
  624. ArrayEnumerator.prototype = {
  625.   _index: 0,
  626.   _contents: [],
  627.  
  628.   hasMoreElements: function() {
  629.     return this._index < this._contents.length;
  630.   },
  631.  
  632.   getNext: function() {
  633.     return this._contents[this._index++];
  634.   }
  635. };
  636.  
  637. /**
  638.  * Trims a prefix from a string.
  639.  * @param   string
  640.  *          The source string
  641.  * @param   prefix
  642.  *          The prefix to remove.
  643.  * @returns The suffix (string - prefix)
  644.  */
  645. function stripPrefix(string, prefix) {
  646.   return string.substr(prefix.length);
  647. }
  648.  
  649. /**
  650.  * Writes a string of text to a file.  A newline will be appended to the data
  651.  * written to the file.  This function only works with ASCII text.
  652.  */
  653. function writeStringToFile(file, text) {
  654.   var fos =
  655.       Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
  656.       createInstance(nsIFileOutputStream);
  657.   var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  658.   if (!file.exists())
  659.     file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  660.   fos.init(file, modeFlags, PERMS_FILE, 0);
  661.   text += "\n";
  662.   fos.write(text, text.length);
  663.   closeSafeOutputStream(fos);
  664. }
  665.  
  666. /**
  667.  * Reads a string of text from a file.  A trailing newline will be removed
  668.  * before the result is returned.  This function only works with ASCII text.
  669.  */
  670. function readStringFromFile(file) {
  671.   var fis =
  672.       Components.classes["@mozilla.org/network/file-input-stream;1"].
  673.       createInstance(nsIFileInputStream);
  674.   var modeFlags = MODE_RDONLY;
  675.   if (!file.exists())
  676.     return null;
  677.   fis.init(file, modeFlags, PERMS_FILE, 0);
  678.   var sis =
  679.       Components.classes["@mozilla.org/scriptableinputstream;1"].
  680.       createInstance(Components.interfaces.nsIScriptableInputStream);
  681.   sis.init(fis);
  682.   var text = sis.read(sis.available());
  683.   sis.close();
  684.   if (text[text.length - 1] == "\n")
  685.     text = text.slice(0, -1);
  686.   return text;
  687. }
  688.  
  689. function getObserverService()
  690. {
  691.   return Components.classes["@mozilla.org/observer-service;1"]
  692.                    .getService(Components.interfaces.nsIObserverService);
  693. }
  694.  
  695. /**
  696.  * Update Patch
  697.  * @param   patch
  698.  *          A <patch> element to initialize this object with
  699.  * @throws if patch has a size of 0
  700.  * @constructor
  701.  */
  702. function UpdatePatch(patch) {
  703.   this._properties = {};
  704.   for (var i = 0; i < patch.attributes.length; ++i) {
  705.     var attr = patch.attributes.item(i);
  706.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  707.     switch (attr.name) {
  708.     case "selected":
  709.       this.selected = attr.value == "true";
  710.       break;
  711.     case "size":
  712.       if (0 == parseInt(attr.value)) {
  713.         LOG("UpdatePatch", "0-sized patch!");
  714.         throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  715.       }
  716.       // fall through
  717.     default:
  718.       this[attr.name] = attr.value;
  719.       break;
  720.     };
  721.   }
  722. }
  723. UpdatePatch.prototype = {
  724.   /**
  725.    * See nsIUpdateService.idl
  726.    */
  727.   serialize: function(updates) {
  728.     var patch = updates.createElementNS(URI_UPDATE_NS, "patch");
  729.     patch.setAttribute("type", this.type);
  730.     patch.setAttribute("URL", this.URL);
  731.     patch.setAttribute("hashFunction", this.hashFunction);
  732.     patch.setAttribute("hashValue", this.hashValue);
  733.     patch.setAttribute("size", this.size);
  734.     patch.setAttribute("selected", this.selected);
  735.     patch.setAttribute("state", this.state);
  736.  
  737.     for (var p in this._properties) {
  738.       if (this._properties[p].present)
  739.         patch.setAttribute(p, this._properties[p].data);
  740.     }
  741.  
  742.     return patch;
  743.   },
  744.  
  745.   /**
  746.    * A hash of custom properties
  747.    */
  748.   _properties: null,
  749.  
  750.   /**
  751.    * See nsIWritablePropertyBag.idl
  752.    */
  753.   setProperty: function(name, value) {
  754.     this._properties[name] = { data: value, present: true };
  755.   },
  756.  
  757.   /**
  758.    * See nsIWritablePropertyBag.idl
  759.    */
  760.   deleteProperty: function(name) {
  761.     if (name in this._properties)
  762.       this._properties[name].present = false;
  763.     else
  764.       throw Components.results.NS_ERROR_FAILURE;
  765.   },
  766.  
  767.   /**
  768.    * See nsIPropertyBag.idl
  769.    */
  770.   get enumerator() {
  771.     var properties = [];
  772.     for (var p in this._properties)
  773.       properties.push(this._properties[p].data);
  774.     return new ArrayEnumerator(properties);
  775.   },
  776.  
  777.   /**
  778.    * See nsIPropertyBag.idl
  779.    */
  780.   getProperty: function(name) {
  781.     if (name in this._properties &&
  782.         this._properties[name].present)
  783.       return this._properties[name].data;
  784.     throw Components.results.NS_ERROR_FAILURE;
  785.   },
  786.  
  787.   /**
  788.    * Returns whether or not the update.status file for this patch exists at the
  789.    * appropriate location.
  790.    */
  791.   get statusFileExists() {
  792.     var statusFile = getUpdatesDir();
  793.     statusFile.append(FILE_UPDATE_STATUS);
  794.     return statusFile.exists();
  795.   },
  796.  
  797.   /**
  798.    * See nsIUpdateService.idl
  799.    */
  800.   get state() {
  801.     if (!this.statusFileExists)
  802.       return STATE_NONE;
  803.     return this._properties.state;
  804.   },
  805.   set state(val) {
  806.     this._properties.state = val;
  807.   },
  808.  
  809.   /**
  810.    * See nsISupports.idl
  811.    */
  812.   QueryInterface: function(iid) {
  813.     if (!iid.equals(Components.interfaces.nsIUpdatePatch) &&
  814.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  815.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  816.         !iid.equals(Components.interfaces.nsISupports))
  817.       throw Components.results.NS_ERROR_NO_INTERFACE;
  818.     return this;
  819.   }
  820. };
  821.  
  822. /**
  823.  * Update
  824.  * Implements nsIUpdate
  825.  * @param   update
  826.  *          An <update> element to initialize this object with
  827.  * @throws if the update contains no patches
  828.  * @constructor
  829.  */
  830. function Update(update) {
  831.   this._properties = {};
  832.   this._patches = [];
  833.   this.installDate = 0;
  834.   this.isCompleteUpdate = false;
  835.   this.channel = "default"
  836.  
  837.   // Null <update>, assume this is a message container and do no
  838.   // further initialization
  839.   if (!update)
  840.     return;
  841.  
  842.   for (var i = 0; i < update.childNodes.length; ++i) {
  843.     var patchElement = update.childNodes.item(i);
  844.     if (patchElement.nodeType != Node.ELEMENT_NODE ||
  845.         patchElement.localName != "patch")
  846.       continue;
  847.  
  848.     patchElement.QueryInterface(Components.interfaces.nsIDOMElement);
  849.     try {
  850.       var patch = new UpdatePatch(patchElement);
  851.     } catch (e) {
  852.       continue;
  853.     }
  854.     this._patches.push(patch);
  855.   }
  856.  
  857.   if (0 == this._patches.length)
  858.     throw Components.results.NS_ERROR_ILLEGAL_VALUE;
  859.  
  860.   for (var i = 0; i < update.attributes.length; ++i) {
  861.     var attr = update.attributes.item(i);
  862.     attr.QueryInterface(Components.interfaces.nsIDOMAttr);
  863.     if (attr.name == "installDate" && attr.value)
  864.       this.installDate = parseInt(attr.value);
  865.     else if (attr.name == "isCompleteUpdate")
  866.       this.isCompleteUpdate = attr.value == "true";
  867.     else if (attr.name == "isSecurityUpdate")
  868.       this.isSecurityUpdate = attr.value == "true";
  869.     else if (attr.name == "detailsURL")
  870.       this._detailsURL = attr.value;
  871.     else if (attr.name == "channel")
  872.       this.channel = attr.value;
  873.     else
  874.       this[attr.name] = attr.value;
  875.   }
  876.  
  877.   // The Update Name is either the string provided by the <update> element, or
  878.   // the string: "<App Name> <Update App Version>"
  879.   var name = "";
  880.   if (update.hasAttribute("name"))
  881.     name = update.getAttribute("name");
  882.   else {
  883.     var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"]
  884.                         .getService(Components.interfaces.nsIStringBundleService);
  885.     var brandBundle = sbs.createBundle(URI_BRAND_PROPERTIES);
  886.     var updateBundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  887.     var appName = brandBundle.GetStringFromName("brandShortName");
  888.     name = updateBundle.formatStringFromName("updateName",
  889.                                              [appName, this.version], 2);
  890.   }
  891.   this.name = name;
  892. }
  893. Update.prototype = {
  894.   /**
  895.    * See nsIUpdateService.idl
  896.    */
  897.   get patchCount() {
  898.     return this._patches.length;
  899.   },
  900.  
  901.   /**
  902.    * See nsIUpdateService.idl
  903.    */
  904.   getPatchAt: function(index) {
  905.     return this._patches[index];
  906.   },
  907.  
  908.   /**
  909.    * See nsIUpdateService.idl
  910.    *
  911.    * We use a copy of the state cached on this object in |_state| only when
  912.    * there is no selected patch, i.e. in the case when we could not load
  913.    * |.activeUpdate| from the update manager for some reason but still have
  914.    * the update.status file to work with.
  915.    */
  916.   _state: "",
  917.   set state(state) {
  918.     if (this.selectedPatch)
  919.       this.selectedPatch.state = state;
  920.     this._state = state;
  921.     return state;
  922.   },
  923.   get state() {
  924.     if (this.selectedPatch)
  925.       return this.selectedPatch.state;
  926.     return this._state;
  927.   },
  928.  
  929.   /**
  930.    * See nsIUpdateService.idl
  931.    */
  932.   errorCode: 0,
  933.  
  934.   /**
  935.    * See nsIUpdateService.idl
  936.    */
  937.   get selectedPatch() {
  938.     for (var i = 0; i < this.patchCount; ++i) {
  939.       if (this._patches[i].selected)
  940.         return this._patches[i];
  941.     }
  942.     return null;
  943.   },
  944.  
  945.   /**
  946.    * See nsIUpdateService.idl
  947.    */
  948.   get detailsURL() {
  949.     if (!this._detailsURL) {
  950.       try {
  951.         // Try using a default details URL supplied by the distribution
  952.         // if the update XML does not supply one.
  953.         var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  954.                                   .getService(Components.interfaces.nsIURLFormatter);
  955.         return formatter.formatURLPref(PREF_APP_UPDATE_URL_DETAILS);
  956.       }
  957.       catch (e) {
  958.       }
  959.     }
  960.     return this._detailsURL || "";
  961.   },
  962.  
  963.   /**
  964.    * See nsIUpdateService.idl
  965.    */
  966.   serialize: function(updates) {
  967.     var update = updates.createElementNS(URI_UPDATE_NS, "update");
  968.     update.setAttribute("type", this.type);
  969.     update.setAttribute("name", this.name);
  970.     update.setAttribute("version", this.version);
  971.     update.setAttribute("platformVersion", this.platformVersion);
  972.     update.setAttribute("extensionVersion", this.extensionVersion);
  973.     update.setAttribute("detailsURL", this.detailsURL);
  974.     update.setAttribute("licenseURL", this.licenseURL);
  975.     update.setAttribute("serviceURL", this.serviceURL);
  976.     update.setAttribute("installDate", this.installDate);
  977.     update.setAttribute("statusText", this.statusText);
  978.     update.setAttribute("buildID", this.buildID);
  979.     update.setAttribute("isCompleteUpdate", this.isCompleteUpdate);
  980.     update.setAttribute("channel", this.channel);
  981.     updates.documentElement.appendChild(update);
  982.  
  983.     for (var p in this._properties) {
  984.       if (this._properties[p].present)
  985.         update.setAttribute(p, this._properties[p].data);
  986.     }
  987.  
  988.     for (var i = 0; i < this.patchCount; ++i)
  989.       update.appendChild(this.getPatchAt(i).serialize(updates));
  990.  
  991.     return update;
  992.   },
  993.  
  994.   /**
  995.    * A hash of custom properties
  996.    */
  997.   _properties: null,
  998.  
  999.   /**
  1000.    * See nsIWritablePropertyBag.idl
  1001.    */
  1002.   setProperty: function(name, value) {
  1003.     this._properties[name] = { data: value, present: true };
  1004.   },
  1005.  
  1006.   /**
  1007.    * See nsIWritablePropertyBag.idl
  1008.    */
  1009.   deleteProperty: function(name) {
  1010.     if (name in this._properties)
  1011.       this._properties[name].present = false;
  1012.     else
  1013.       throw Components.results.NS_ERROR_FAILURE;
  1014.   },
  1015.  
  1016.   /**
  1017.    * See nsIPropertyBag.idl
  1018.    */
  1019.   get enumerator() {
  1020.     var properties = [];
  1021.     for (var p in this._properties)
  1022.       properties.push(this._properties[p].data);
  1023.     return new ArrayEnumerator(properties);
  1024.   },
  1025.  
  1026.   /**
  1027.    * See nsIPropertyBag.idl
  1028.    */
  1029.   getProperty: function(name) {
  1030.     if (name in this._properties &&
  1031.         this._properties[name].present)
  1032.       return this._properties[name].data;
  1033.     throw Components.results.NS_ERROR_FAILURE;
  1034.   },
  1035.  
  1036.   /**
  1037.    * See nsISupports.idl
  1038.    */
  1039.   QueryInterface: function(iid) {
  1040.     if (!iid.equals(Components.interfaces.nsIUpdate) &&
  1041.         !iid.equals(Components.interfaces.nsIPropertyBag) &&
  1042.         !iid.equals(Components.interfaces.nsIWritablePropertyBag) &&
  1043.         !iid.equals(Components.interfaces.nsISupports))
  1044.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1045.     return this;
  1046.   }
  1047. };
  1048.  
  1049. /**
  1050.  * UpdateService
  1051.  * A Service for managing the discovery and installation of software updates.
  1052.  * @constructor
  1053.  */
  1054. function UpdateService() {
  1055.   gApp  = Components.classes["@mozilla.org/xre/app-info;1"]
  1056.                     .getService(Components.interfaces.nsIXULAppInfo)
  1057.                     .QueryInterface(Components.interfaces.nsIXULRuntime);
  1058.   gPref = Components.classes["@mozilla.org/preferences-service;1"]
  1059.                     .getService(Components.interfaces.nsIPrefBranch2);
  1060.   gConsole = Components.classes["@mozilla.org/consoleservice;1"]
  1061.                        .getService(Components.interfaces.nsIConsoleService);
  1062.  
  1063.   // Not all builds have a known ABI
  1064.   try {
  1065.     gABI = gApp.XPCOMABI;
  1066.   }
  1067.   catch (e) {
  1068.     LOG("UpdateService", "XPCOM ABI unknown: updates are not possible.");
  1069.   }
  1070.  
  1071.   var osVersion;
  1072.   var sysInfo = Components.classes["@mozilla.org/system-info;1"]
  1073.                           .getService(Components.interfaces.nsIPropertyBag2);
  1074.   try {
  1075.     osVersion = sysInfo.getProperty("name") + " " + sysInfo.getProperty("version");
  1076.   }
  1077.   catch (e) {
  1078.     LOG("UpdateService", "OS Version unknown: updates are not possible.");
  1079.   }
  1080.  
  1081.   if (osVersion) {
  1082.     try {
  1083.       osVersion += " (" + sysInfo.getProperty("secondaryLibrary") + ")";
  1084.     }
  1085.     catch (e) {
  1086.       // Not all platforms have a secondary widget library, so an error is nothing to worry about.
  1087.     }
  1088.     gOSVersion = encodeURIComponent(osVersion);
  1089.   }
  1090.  
  1091. //@line 1079 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  1092.  
  1093.   // Start the update timer only after a profile has been selected so that the
  1094.   // appropriate values for the update check are read from the user's profile.
  1095.   var os = getObserverService();
  1096.  
  1097.   os.addObserver(this, "profile-after-change", false);
  1098.  
  1099.   // Observe xpcom-shutdown to unhook pref branch observers above to avoid
  1100.   // shutdown leaks.
  1101.   os.addObserver(this, "xpcom-shutdown", false);
  1102. }
  1103.  
  1104. UpdateService.prototype = {
  1105.   /**
  1106.    * The downloader we are using to download updates. There is only ever one of
  1107.    * these.
  1108.    */
  1109.   _downloader: null,
  1110.  
  1111.   /**
  1112.    * Handle Observer Service notifications
  1113.    * @param   subject
  1114.    *          The subject of the notification
  1115.    * @param   topic
  1116.    *          The notification name
  1117.    * @param   data
  1118.    *          Additional data
  1119.    */
  1120.   observe: function(subject, topic, data) {
  1121.     var os = getObserverService();
  1122.  
  1123.     switch (topic) {
  1124.     case "profile-after-change":
  1125.       os.removeObserver(this, "profile-after-change");
  1126.       this._start();
  1127.       break;
  1128.     case "xpcom-shutdown":
  1129.       os.removeObserver(this, "xpcom-shutdown");
  1130.  
  1131.       // Release Services
  1132.       gApp      = null;
  1133.       gPref     = null;
  1134.       gConsole  = null;
  1135.       break;
  1136.     }
  1137.   },
  1138.  
  1139.   /**
  1140.    * Start the Update Service
  1141.    */
  1142.   _start: function() {
  1143.     // Start logging
  1144.     this._initLoggingPrefs();
  1145.  
  1146.     // Clean up any extant updates
  1147.     this._postUpdateProcessing();
  1148.  
  1149.     // Register a background update check timer
  1150.     var tm =
  1151.         Components.classes["@mozilla.org/updates/timer-manager;1"]
  1152.                   .getService(Components.interfaces.nsIUpdateTimerManager);
  1153.     var interval = getPref("getIntPref", PREF_APP_UPDATE_INTERVAL, 86400);
  1154.     tm.registerTimer("background-update-timer", this, interval);
  1155.  
  1156.     // Resume fetching...
  1157.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1158.                         .getService(Components.interfaces.nsIUpdateManager);
  1159.     var activeUpdate = um.activeUpdate;
  1160.     if (activeUpdate) {
  1161.       var status = this.downloadUpdate(activeUpdate, true);
  1162.       if (status == STATE_NONE)
  1163.         cleanupActiveUpdate();
  1164.     }
  1165.   },
  1166.  
  1167.   /**
  1168.    * Perform post-processing on updates lingering in the updates directory
  1169.    * from a previous browser session - either report install failures (and
  1170.    * optionally attempt to fetch a different version if appropriate) or
  1171.    * notify the user of install success.
  1172.    */
  1173.   _postUpdateProcessing: function() {
  1174.     // Detect installation failures and notify
  1175.  
  1176.     // Bail out if we don't have appropriate permissions
  1177.     if (!this.canUpdate)
  1178.       return;
  1179.  
  1180.     var status = readStatusFile(getUpdatesDir());
  1181.  
  1182.     // Make sure to cleanup after an update that failed for an unknown reason
  1183.     if (status == "null")
  1184.       status = null;
  1185.  
  1186.     var updRootKey = null;
  1187. //@line 1175 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  1188.     function findPreviousUpdate(key) {
  1189.       var updateDir = getUpdatesDir(key);
  1190.       if (updateDir.exists()) {
  1191.         status = readStatusFile(updateDir);
  1192.         // Previous download should succeed. Otherwise, we will not be here!
  1193.         if (status == STATE_SUCCEEDED)
  1194.           updRootKey = key;
  1195.         else
  1196.           status = null;
  1197.       }
  1198.     }
  1199.  
  1200.     // required when updating from Fx 2.0.0.1 to 2.0.0.3 (or later)
  1201.     // on Windows Vista.
  1202.     if (status == null)
  1203.       findPreviousUpdate(KEY_UAPPDATA);
  1204.  
  1205.     // required to migrate from older versions.
  1206.     if (status == null)
  1207.       findPreviousUpdate(KEY_APPDIR);
  1208. //@line 1196 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  1209.  
  1210.     if (status == STATE_DOWNLOADING) {
  1211.       LOG("UpdateService", "_postUpdateProcessing: Downloading patch, resuming...");
  1212.     }
  1213.     else if (status != null) {
  1214.       // null status means the update.status file is not present, because either:
  1215.       // 1) no update was performed, and so there's no UI to show
  1216.       // 2) an update was attempted but failed during checking, transfer or
  1217.       //    verification, and was cleaned up at that point, and UI notifying of
  1218.       //    that error was shown at that stage.
  1219.       var um =
  1220.           Components.classes["@mozilla.org/updates/update-manager;1"].
  1221.           getService(Components.interfaces.nsIUpdateManager);
  1222.       var prompter =
  1223.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  1224.           createInstance(Components.interfaces.nsIUpdatePrompt);
  1225.  
  1226.       var shouldCleanup = true;
  1227.       var update = um.activeUpdate;
  1228.       if (!update) {
  1229.         update = new Update(null);
  1230.       }
  1231.       update.state = status;
  1232.       var sbs =
  1233.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  1234.           getService(Components.interfaces.nsIStringBundleService);
  1235.       var bundle = sbs.createBundle(URI_UPDATES_PROPERTIES);
  1236.       if (status == STATE_SUCCEEDED) {
  1237.         update.statusText = bundle.GetStringFromName("installSuccess");
  1238.  
  1239.         // Dig through the update history to find the patch that was just
  1240.         // installed and update its metadata.
  1241.         for (var i = 0; i < um.updateCount; ++i) {
  1242.           var umUpdate = um.getUpdateAt(i);
  1243.           if (umUpdate && umUpdate.version == update.version &&
  1244.                           umUpdate.buildID == update.buildID) {
  1245.             umUpdate.statusText = update.statusText;
  1246.             break;
  1247.           }
  1248.         }
  1249.  
  1250.         LOG("UpdateService", "_postUpdateProcessing: Install Succeeded, Showing UI");
  1251.         prompter.showUpdateInstalled(update);
  1252. //@line 1243 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  1253.         // Perform platform-specific post-update processing.
  1254.         if (POST_UPDATE_CONTRACTID in Components.classes) {
  1255.           Components.classes[POST_UPDATE_CONTRACTID].
  1256.               createInstance(Components.interfaces.nsIRunnable).run();
  1257.         }
  1258. //@line 1249 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  1259.  
  1260.         // Done with this update. Clean it up.
  1261.         cleanupActiveUpdate(updRootKey);
  1262.       }
  1263.       else {
  1264.         // If we hit an error, then the error code will be included in the
  1265.         // status string following a colon.  If we had an I/O error, then we
  1266.         // assume that the patch is not invalid, and we restage the patch so
  1267.         // that it can be attempted again the next time we restart.
  1268.         var ary = status.split(": ");
  1269.         update.state = ary[0];
  1270.         if (update.state == STATE_FAILED && ary[1]) {
  1271.           update.errorCode = ary[1];
  1272.           if (update.errorCode == WRITE_ERROR) {
  1273.             prompter.showUpdateError(update);
  1274.             writeStatusFile(getUpdatesDir(), update.state = STATE_PENDING);
  1275.             return;
  1276.           }
  1277.         }
  1278.  
  1279.         // Something went wrong with the patch application process.
  1280.         cleanupActiveUpdate();
  1281.  
  1282.         update.statusText = bundle.GetStringFromName("patchApplyFailure");
  1283.         var oldType = update.selectedPatch ? update.selectedPatch.type
  1284.                                            : "complete";
  1285.         if (update.selectedPatch && oldType == "partial") {
  1286.           // Partial patch application failed, try downloading the complete
  1287.           // update in the background instead.
  1288.           LOG("UpdateService", "_postUpdateProcessing: Install of Partial Patch " +
  1289.               "failed, downloading Complete Patch and maybe showing UI");
  1290.           var status = this.downloadUpdate(update, true);
  1291.           if (status == STATE_NONE)
  1292.             cleanupActiveUpdate();
  1293.         }
  1294.         else {
  1295.           LOG("UpdateService", "_postUpdateProcessing: Install of Complete or " +
  1296.               "only patch failed. Showing error.");
  1297.         }
  1298.         update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  1299.         update.setProperty("patchingFailed", oldType);
  1300.         prompter.showUpdateError(update);
  1301.       }
  1302.     }
  1303.     else {
  1304.       LOG("UpdateService", "_postUpdateProcessing: No Status, No Update");
  1305.     }
  1306.   },
  1307.  
  1308.   /**
  1309.    * Initialize Logging preferences, formatted like so:
  1310.    *  app.update.log.<moduleName> = <true|false>
  1311.    */
  1312.   _initLoggingPrefs: function() {
  1313.     try {
  1314.       var ps = Components.classes["@mozilla.org/preferences-service;1"]
  1315.                         .getService(Components.interfaces.nsIPrefService);
  1316.       var logBranch = ps.getBranch(PREF_APP_UPDATE_LOG_BRANCH);
  1317.       var modules = logBranch.getChildList("", { value: 0 });
  1318.  
  1319.       for (var i = 0; i < modules.length; ++i) {
  1320.         if (logBranch.prefHasUserValue(modules[i]))
  1321.           gLogEnabled[modules[i]] = logBranch.getBoolPref(modules[i]);
  1322.       }
  1323.     }
  1324.     catch (e) {
  1325.     }
  1326.   },
  1327.  
  1328.   /**
  1329.    * Notified when a timer fires
  1330.    * @param   timer
  1331.    *          The timer that fired
  1332.    */
  1333.   notify: function(timer) {
  1334.     // If a download is in progress, then do nothing.
  1335.     if (this.isDownloading || this._downloader && this._downloader.patchIsStaged)
  1336.       return;
  1337.  
  1338.     var self = this;
  1339.     var listener = {
  1340.       /**
  1341.        * See nsIUpdateService.idl
  1342.        */
  1343.       onProgress: function(request, position, totalSize) {
  1344.       },
  1345.  
  1346.       /**
  1347.        * See nsIUpdateService.idl
  1348.        */
  1349.       onCheckComplete: function(request, updates, updateCount) {
  1350.         self._selectAndInstallUpdate(updates);
  1351.       },
  1352.  
  1353.       /**
  1354.        * See nsIUpdateService.idl
  1355.        */
  1356.       onError: function(request, update) {
  1357.         LOG("Checker", "Error during background update: " + update.statusText);
  1358.       },
  1359.     }
  1360.     this.backgroundChecker.checkForUpdates(listener, false);
  1361.   },
  1362.  
  1363.   /**
  1364.    * Determine whether or not an update requires user confirmation before it
  1365.    * can be installed.
  1366.    * @param   update
  1367.    *          The update to be installed
  1368.    * @returns true if a prompt UI should be shown asking the user if they want
  1369.    *          to install the update, false if the update should just be
  1370.    *          silently downloaded and installed.
  1371.    */
  1372.   _shouldPrompt: function(update) {
  1373.     // There are two possible outcomes here:
  1374.     // 1. download and install the update automatically
  1375.     // 2. alert the user about the presence of an update before doing anything
  1376.     //
  1377.     // The outcome we follow is determined as follows:
  1378.     //
  1379.     // Note:  all Major updates require notification and confirmation
  1380.     //
  1381.     // Update Type      Mode      Incompatible    Outcome
  1382.     // Major            0         Yes or No       Notify and Confirm
  1383.     // Major            1         No              Notify and Confirm
  1384.     // Major            1         Yes             Notify and Confirm
  1385.     // Major            2         Yes or No       Notify and Confirm
  1386.     // Minor            0         Yes or No       Auto Install
  1387.     // Minor            1         No              Auto Install
  1388.     // Minor            1         Yes             Notify and Confirm
  1389.     // Minor            2         No              Auto Install
  1390.     // Minor            2         Yes             Notify and Confirm
  1391.     //
  1392.     // In addition, if there is a license associated with an update, regardless
  1393.     // of type it must be agreed to.
  1394.     //
  1395.     // If app.update.enabled is set to false, an update check is not performed
  1396.     // at all, and so none of the decision making above is entered into.
  1397.     //
  1398.     if (update.type == "major") {
  1399.       LOG("Checker", "_shouldPrompt: Prompting because it is a major update");
  1400.       return true;
  1401.     }
  1402.  
  1403.     update.QueryInterface(Components.interfaces.nsIPropertyBag);
  1404.     try {
  1405.       var licenseAccepted = update.getProperty("licenseAccepted") == "true";
  1406.     }
  1407.     catch (e) {
  1408.       licenseAccepted = false;
  1409.     }
  1410.  
  1411.     var updateEnabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1412.     if (!updateEnabled) {
  1413.       LOG("Checker", "_shouldPrompt: Not prompting because update is " +
  1414.           "disabled");
  1415.       return false;
  1416.     }
  1417.  
  1418.     // User has turned off automatic download and install
  1419.     var autoEnabled = getPref("getBoolPref", PREF_APP_UPDATE_AUTO, true);
  1420.     if (!autoEnabled) {
  1421.       LOG("Checker", "_shouldPrompt: Prompting because auto install is disabled");
  1422.       return true;
  1423.     }
  1424.  
  1425.     switch (getPref("getIntPref", PREF_APP_UPDATE_MODE, 1)) {
  1426.     case 1:
  1427.       // Mode 1 is do not prompt only if there are no incompatibilities
  1428.       // releases
  1429.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1430.       return !isCompatible(update);
  1431.     case 2:
  1432.       // Mode 2 is do not prompt only if there are no incompatibilities
  1433.       LOG("Checker", "_shouldPrompt: Prompting if there are incompatibilities");
  1434.       return !isCompatible(update);
  1435.     }
  1436.     // Mode 0 is do not prompt regardless of incompatibilities
  1437.     LOG("Checker", "_shouldPrompt: Not prompting the user - they choose to " +
  1438.         "ignore incompatibilities");
  1439.     return false;
  1440.   },
  1441.  
  1442.   /**
  1443.    * Determine which of the specified updates should be installed.
  1444.    * @param   updates
  1445.    *          An array of available updates
  1446.    */
  1447.   selectUpdate: function(updates) {
  1448.     if (updates.length == 0)
  1449.       return null;
  1450.  
  1451.     // Choose the newest of the available minor and major updates.
  1452.     var majorUpdate = null, minorUpdate = null;
  1453.     var newestMinor = updates[0], newestMajor = updates[0];
  1454.  
  1455.     var vc = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  1456.                        .getService(Components.interfaces.nsIVersionComparator);
  1457.     for (var i = 0; i < updates.length; ++i) {
  1458.       if (updates[i].type == "major" &&
  1459.           vc.compare(newestMajor.version, updates[i].version) <= 0)
  1460.         majorUpdate = newestMajor = updates[i];
  1461.       if (updates[i].type == "minor" &&
  1462.           vc.compare(newestMinor.version, updates[i].version) <= 0)
  1463.         minorUpdate = newestMinor = updates[i];
  1464.     }
  1465.  
  1466.     // IMPORTANT
  1467.     // If there's a minor update, always try and fetch that one first,
  1468.     // otherwise use the newest major update.
  1469.     // selectUpdate() only returns one update.
  1470.     // if major were to trump minor, and we said "never" to the major
  1471.     // we'd never get the minor update, since selectUpdate()
  1472.     // would return the major update that the user said "never" to
  1473.     // (shadowing the important minor update with security fixes)
  1474.     return minorUpdate || majorUpdate;
  1475.   },
  1476.  
  1477.   /**
  1478.    * Determine which of the specified updates should be installed and
  1479.    * begin the download/installation process, optionally prompting the
  1480.    * user for permission if required.
  1481.    * @param   updates
  1482.    *          An array of available updates
  1483.    */
  1484.   _selectAndInstallUpdate: function(updates) {
  1485.     // Don't prompt if there's an active update - the user is already
  1486.     // aware and is downloading, or performed some user action to prevent
  1487.     // notification.
  1488.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  1489.                        .getService(Components.interfaces.nsIUpdateManager);
  1490.     if (um.activeUpdate)
  1491.       return;
  1492.  
  1493.     var update = this.selectUpdate(updates, updates.length);
  1494.     if (!update)
  1495.       return;
  1496.  
  1497.     // check if the user said "never" to this version
  1498.     // this check is done here, and not in selectUpdate() so that
  1499.     // the user can get an upgrade they said "never" to if they
  1500.     // manually do "Check for Updates..."
  1501.     // note, selectUpdate() only returns one update.
  1502.     // but in selectUpdate(), minor updates trump major updates
  1503.     // if major trumps minor, and we said "never" to the major
  1504.     // we'd never see the minor update.
  1505.     //
  1506.     // note, the never decision should only apply to major updates
  1507.     // see bug #350636 for a scenario where this could potentially
  1508.     // be an issue
  1509.     //
  1510.     // fix for bug #359093
  1511.     // version might one day come back from AUS as an
  1512.     // arbitrary (and possibly non ascii) string, so we need to encode it
  1513.     var neverPrefName = PREF_UPDATE_NEVER_BRANCH + encodeURIComponent(update.version);
  1514.     var never = getPref("getBoolPref", neverPrefName, false);
  1515.     if (never && update.type == "major")
  1516.       return;
  1517.  
  1518.     if (this._shouldPrompt(update))
  1519.       showPromptIfNoIncompatibilities(update);
  1520.     else {
  1521.       LOG("UpdateService", "_selectAndInstallUpdate: No need to show prompt, just download update");
  1522.       var status = this.downloadUpdate(update, true);
  1523.       if (status == STATE_NONE)
  1524.         cleanupActiveUpdate();
  1525.     }
  1526.   },
  1527.  
  1528.   /**
  1529.    * The Checker used for background update checks.
  1530.    */
  1531.   _backgroundChecker: null,
  1532.  
  1533.   /**
  1534.    * See nsIUpdateService.idl
  1535.    */
  1536.   get backgroundChecker() {
  1537.     if (!this._backgroundChecker)
  1538.       this._backgroundChecker = new Checker();
  1539.     return this._backgroundChecker;
  1540.   },
  1541.  
  1542.   /**
  1543.    * See nsIUpdateService.idl
  1544.    */
  1545.   get canUpdate() {
  1546.     try {
  1547.       var appDirFile = getUpdateFile([FILE_PERMS_TEST]);
  1548.       LOG("UpdateService", "canUpdate?  testing " + appDirFile.path);
  1549.       if (!appDirFile.exists()) {
  1550.         appDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1551.         appDirFile.remove(false);
  1552.       }
  1553.       var updateDir = getUpdatesDir();
  1554.       var upDirFile = updateDir.clone();
  1555.       upDirFile.append(FILE_PERMS_TEST);
  1556.       LOG("UpdateService", "canUpdate?  testing " + upDirFile.path);
  1557.       if (!upDirFile.exists()) {
  1558.         upDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1559.         upDirFile.remove(false);
  1560.       }
  1561. //@line 1552 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  1562.       var sysInfo =
  1563.         Components.classes["@mozilla.org/system-info;1"]
  1564.                   .getService(Components.interfaces.nsIPropertyBag2);
  1565.  
  1566.       // Example windowsVersion:  Windows XP == 5.1
  1567.       var windowsVersion = sysInfo.getProperty("version");
  1568.       LOG("UpdateService", "canUpdate?  windowsVersion = " + windowsVersion);
  1569.  
  1570.       // For Vista, updates can be performed to a location requiring 
  1571.       // admin privileges by requesting elevation via the UAC prompt when 
  1572.       // launching updater.exe if the appDir is under the Program Files 
  1573.       // directory (e.g. C:\Program Files\) and UAC is turned on and 
  1574.       // we can elevate (e.g. user has a split token)
  1575.       //
  1576.       // Note: this does note attempt to handle the case where UAC is
  1577.       // turned on and the installation directory is in a restricted
  1578.       // location that requires admin privileges to update other than 
  1579.       // Program Files.
  1580.  
  1581.       var userCanElevate = false;
  1582.  
  1583.       if (parseFloat(windowsVersion) >= 6) {
  1584.         try {
  1585.           var fileLocator = 
  1586.             Components.classes["@mozilla.org/file/directory_service;1"]
  1587.                       .getService(Components.interfaces.nsIProperties);
  1588.           // KEY_UPDROOT will fail and throw an exception if
  1589.           // appDir is not under the Program Files, so we rely on that
  1590.           var dir = fileLocator.get(KEY_UPDROOT, Components.interfaces.nsIFile);
  1591.           // appDir is under Program Files, so check if the user can elevate
  1592.           userCanElevate = 
  1593.             gApp.QueryInterface(Components.interfaces.nsIWinAppHelper)
  1594.                 .userCanElevate;
  1595.           LOG("UpdateService", 
  1596.               "canUpdate?  on Vista, userCanElevate = " + userCanElevate);
  1597.         }
  1598.         catch (ex) {
  1599.           // When the installation directory is not under Program Files,
  1600.           // fall through to checking if write access to the 
  1601.           // installation directory is available.
  1602.           LOG("UpdateService", 
  1603.               "canUpdate?  on Vista, appDir is not under the Program Files");
  1604.         }
  1605.       }
  1606.  
  1607.       // On Windows, we no longer store the update under the app dir
  1608.       // if the app dir is under C:\Program Files.
  1609.       //
  1610.       // If we are on Windows (including Vista, if we can't elevate)
  1611.       // we need to check that
  1612.       // we can create and remove files from the actual app directory
  1613.       // (like C:\Program Files\Mozilla Firefox).  If we can't
  1614.       // (because this user is not an adminstrator, for example)
  1615.       // canUpdate() should return false.
  1616.       //
  1617.       // For Vista, we perform this check to enable updating the 
  1618.       // application when the user has write access to the installation 
  1619.       // directory under the following scenarios:
  1620.       // 1) the installation directory is not under Program Files 
  1621.       //    (e.g. C:\Program Files)
  1622.       // 2) UAC is turned off
  1623.       // 3) UAC is turned on and the user is not an admin 
  1624.       //    (e.g. the user does not have a split token)
  1625.       // 4) UAC is turned on and the user is already elevated,
  1626.       //    so they can't be elevated again.
  1627.       if (!userCanElevate) {
  1628.         // if we're unable to create the test file
  1629.         // the code below will throw an exception 
  1630.         var actualAppDir = getDir(KEY_APPDIR, []);
  1631.         var actualAppDirFile = actualAppDir.clone();
  1632.         actualAppDirFile.append(FILE_PERMS_TEST);
  1633.         LOG("UpdateService", "canUpdate?  testing " + actualAppDirFile.path);
  1634.         if (!actualAppDirFile.exists()) {
  1635.           actualAppDirFile.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1636.           actualAppDirFile.remove(false);
  1637.         }
  1638.       }
  1639. //@line 1630 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  1640.     }
  1641.     catch (e) {
  1642.        LOG("UpdateService", "can't update, no privileges: " + e);
  1643.       // No write privileges to install directory
  1644.       return false;
  1645.     }
  1646.     // If the administrator has locked the app update functionality
  1647.     // OFF - this is not just a user setting, so disable the manual
  1648.     // UI too.
  1649.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true);
  1650.     if (!enabled && gPref.prefIsLocked(PREF_APP_UPDATE_ENABLED)) {
  1651.       LOG("UpdateService", "can't update, disabled by pref");
  1652.       return false;
  1653.     }
  1654.  
  1655.     // If we don't know the binary platform we're updating, we can't update.
  1656.     if (!gABI) {
  1657.       LOG("UpdateService", "can't update, unknown ABI");
  1658.       return false;
  1659.     }
  1660.  
  1661.     // If we don't know the OS version we're updating, we can't update.
  1662.     if (!gOSVersion) {
  1663.       LOG("UpdateService", "can't update, unknown OS version");
  1664.       return false;
  1665.     }
  1666.  
  1667.     LOG("UpdateService", "can update");
  1668.     return true;
  1669.   },
  1670.  
  1671.   /**
  1672.    * See nsIUpdateService.idl
  1673.    */
  1674.   addDownloadListener: function(listener) {
  1675.     if (!this._downloader) {
  1676.       LOG("UpdateService", "addDownloadListener: no downloader!\n");
  1677.       return;
  1678.     }
  1679.     this._downloader.addDownloadListener(listener);
  1680.   },
  1681.  
  1682.   /**
  1683.    * See nsIUpdateService.idl
  1684.    */
  1685.   removeDownloadListener: function(listener) {
  1686.     if (!this._downloader) {
  1687.       LOG("UpdateService", "removeDownloadListener: no downloader!\n");
  1688.       return;
  1689.     }
  1690.     this._downloader.removeDownloadListener(listener);
  1691.   },
  1692.  
  1693.   /**
  1694.    * See nsIUpdateService.idl
  1695.    */
  1696.   downloadUpdate: function(update, background) {
  1697.     if (!update)
  1698.       throw Components.results.NS_ERROR_NULL_POINTER;
  1699.     if (this.isDownloading) {
  1700.       if (update.isCompleteUpdate == this._downloader.isCompleteUpdate &&
  1701.           background == this._downloader.background) {
  1702.         LOG("UpdateService", "no support for downloading more than one update at a time");
  1703.         return readStatusFile(getUpdatesDir());
  1704.       }
  1705.       this._downloader.cancel();
  1706.     }
  1707.     this._downloader = new Downloader(background);
  1708.     return this._downloader.downloadUpdate(update);
  1709.   },
  1710.  
  1711.   /**
  1712.    * See nsIUpdateService.idl
  1713.    */
  1714.   pauseDownload: function() {
  1715.     if (this.isDownloading)
  1716.       this._downloader.cancel();
  1717.   },
  1718.  
  1719.   /**
  1720.    * See nsIUpdateService.idl
  1721.    */
  1722.   get isDownloading() {
  1723.     return this._downloader && this._downloader.isBusy;
  1724.   },
  1725.  
  1726.   /**
  1727.    * See nsISupports.idl
  1728.    */
  1729.   QueryInterface: function(iid) {
  1730.     if (!iid.equals(Components.interfaces.nsIApplicationUpdateService) &&
  1731.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  1732.         !iid.equals(Components.interfaces.nsIObserver) &&
  1733.         !iid.equals(Components.interfaces.nsISupports))
  1734.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1735.     return this;
  1736.   }
  1737. };
  1738.  
  1739. /**
  1740.  * A service to manage active and past updates.
  1741.  * @constructor
  1742.  */
  1743. function UpdateManager() {
  1744.   // Ensure the Active Update file is loaded
  1745.   var updates = this._loadXMLFileIntoArray(getUpdateFile([FILE_UPDATE_ACTIVE]));
  1746.   if (updates.length > 0)
  1747.     this._activeUpdate = updates[0];
  1748. }
  1749. UpdateManager.prototype = {
  1750.   /**
  1751.    * All previously downloaded and installed updates, as an array of nsIUpdate
  1752.    * objects.
  1753.    */
  1754.   _updates: null,
  1755.  
  1756.   /**
  1757.    * The current actively downloading/installing update, as a nsIUpdate object.
  1758.    */
  1759.   _activeUpdate: null,
  1760.  
  1761.   /**
  1762.    * Loads an updates.xml formatted file into an array of nsIUpdate items.
  1763.    * @param   file
  1764.    *          A nsIFile for the updates.xml file
  1765.    * @returns The array of nsIUpdate items held in the file.
  1766.    */
  1767.   _loadXMLFileIntoArray: function(file) {
  1768.     if (!file.exists()) {
  1769.       LOG("UpdateManager", "_loadXMLFileIntoArray: XML File does not exist");
  1770.       return [];
  1771.     }
  1772.  
  1773.     var result = [];
  1774.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
  1775.                                .createInstance(Components.interfaces.nsIFileInputStream);
  1776.     fileStream.init(file, MODE_RDONLY, PERMS_FILE, 0);
  1777.     try {
  1778.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1779.                             .createInstance(Components.interfaces.nsIDOMParser);
  1780.       var doc = parser.parseFromStream(fileStream, "UTF-8", fileStream.available(), "text/xml");
  1781.  
  1782.       var updateCount = doc.documentElement.childNodes.length;
  1783.       for (var i = 0; i < updateCount; ++i) {
  1784.         var updateElement = doc.documentElement.childNodes.item(i);
  1785.         if (updateElement.nodeType != Node.ELEMENT_NODE ||
  1786.             updateElement.localName != "update")
  1787.           continue;
  1788.  
  1789.         updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  1790.         try {
  1791.           var update = new Update(updateElement);
  1792.         } catch (e) {
  1793.           LOG("UpdateManager", "_loadXMLFileIntoArray: invalid update");
  1794.           continue;
  1795.         }
  1796.         result.push(new Update(updateElement));
  1797.       }
  1798.     }
  1799.     catch (e) {
  1800.       LOG("UpdateManager", "_loadXMLFileIntoArray: Error constructing update list " +
  1801.           e);
  1802.     }
  1803.     fileStream.close();
  1804.     return result;
  1805.   },
  1806.  
  1807.   /**
  1808.    * Load the update manager, initializing state from state files.
  1809.    */
  1810.   _ensureUpdates: function() {
  1811.     if (!this._updates) {
  1812.       this._updates = this._loadXMLFileIntoArray(getUpdateFile(
  1813.                         [FILE_UPDATES_DB]));
  1814.  
  1815.       // Make sure that any active update is part of our updates list
  1816.       var active = this.activeUpdate;
  1817.       if (active)
  1818.         this._addUpdate(active);
  1819.     }
  1820.   },
  1821.  
  1822.   /**
  1823.    * See nsIUpdateService.idl
  1824.    */
  1825.   getUpdateAt: function(index) {
  1826.     this._ensureUpdates();
  1827.     return this._updates[index];
  1828.   },
  1829.  
  1830.   /**
  1831.    * See nsIUpdateService.idl
  1832.    */
  1833.   get updateCount() {
  1834.     this._ensureUpdates();
  1835.     return this._updates.length;
  1836.   },
  1837.  
  1838.   /**
  1839.    * See nsIUpdateService.idl
  1840.    */
  1841.   get activeUpdate() {
  1842.     if (this._activeUpdate &&
  1843.         this._activeUpdate.channel != getUpdateChannel()) {
  1844.       // User switched channels, clear out any old active updates and remove
  1845.       // partial downloads
  1846.       this._activeUpdate = null;
  1847.  
  1848.       // Destroy the updates directory, since we're done with it.
  1849.       cleanUpUpdatesDir();
  1850.     }
  1851.     return this._activeUpdate;
  1852.   },
  1853.   set activeUpdate(activeUpdate) {
  1854.     this._addUpdate(activeUpdate);
  1855.     this._activeUpdate = activeUpdate;
  1856.     if (!activeUpdate) {
  1857.       // If |activeUpdate| is null, we have updated both lists - the active list
  1858.       // and the history list, so we want to write both files.
  1859.       this.saveUpdates();
  1860.     }
  1861.     else
  1862.       this._writeUpdatesToXMLFile([this._activeUpdate],
  1863.                                   getUpdateFile([FILE_UPDATE_ACTIVE]));
  1864.     return activeUpdate;
  1865.   },
  1866.  
  1867.   /**
  1868.    * Add an update to the Updates list. If the item already exists in the list,
  1869.    * replace the existing value with the new value.
  1870.    * @param   update
  1871.    *          The nsIUpdate object to add.
  1872.    */
  1873.   _addUpdate: function(update) {
  1874.     if (!update)
  1875.       return;
  1876.     this._ensureUpdates();
  1877.     if (this._updates) {
  1878.       for (var i = 0; i < this._updates.length; ++i) {
  1879.         if (this._updates[i] &&
  1880.             this._updates[i].version == update.version &&
  1881.             this._updates[i].buildID == update.buildID) {
  1882.           // Replace the existing entry with the new value, updating
  1883.           // all metadata.
  1884.           this._updates[i] = update;
  1885.           return;
  1886.         }
  1887.       }
  1888.     }
  1889.     // Otherwise add it to the front of the list.
  1890.     if (update)
  1891.       this._updates = [update].concat(this._updates);
  1892.   },
  1893.  
  1894.   /**
  1895.    * Serializes an array of updates to an XML file
  1896.    * @param   updates
  1897.    *          An array of nsIUpdate objects
  1898.    * @param   file
  1899.    *          The nsIFile object to serialize to
  1900.    */
  1901.   _writeUpdatesToXMLFile: function(updates, file) {
  1902.     var fos = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
  1903.                         .createInstance(Components.interfaces.nsIFileOutputStream);
  1904.     var modeFlags = MODE_WRONLY | MODE_CREATE | MODE_TRUNCATE;
  1905.     if (!file.exists())
  1906.       file.create(nsILocalFile.NORMAL_FILE_TYPE, PERMS_FILE);
  1907.     fos.init(file, modeFlags, PERMS_FILE, 0);
  1908.  
  1909.     try {
  1910.       var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"]
  1911.                             .createInstance(Components.interfaces.nsIDOMParser);
  1912.       const EMPTY_UPDATES_DOCUMENT = "<?xml version=\"1.0\"?><updates xmlns=\"http://www.mozilla.org/2005/app-update\"></updates>";
  1913.       var doc = parser.parseFromString(EMPTY_UPDATES_DOCUMENT, "text/xml");
  1914.  
  1915.       for (var i = 0; i < updates.length; ++i) {
  1916.         if (updates[i])
  1917.           doc.documentElement.appendChild(updates[i].serialize(doc));
  1918.       }
  1919.  
  1920.       var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"]
  1921.                                 .createInstance(Components.interfaces.nsIDOMSerializer);
  1922.       serializer.serializeToStream(doc.documentElement, fos, null);
  1923.     }
  1924.     catch (e) {
  1925.     }
  1926.  
  1927.     closeSafeOutputStream(fos);
  1928.   },
  1929.  
  1930.   /**
  1931.    * See nsIUpdateService.idl
  1932.    */
  1933.   saveUpdates: function() {
  1934.     this._writeUpdatesToXMLFile([this._activeUpdate],
  1935.                                 getUpdateFile([FILE_UPDATE_ACTIVE]));
  1936.     if (this._updates) {
  1937.       this._writeUpdatesToXMLFile(this._updates.slice(0, 10),
  1938.                                   getUpdateFile([FILE_UPDATES_DB]));
  1939.     }
  1940.   },
  1941.  
  1942.   /**
  1943.    * See nsISupports.idl
  1944.    */
  1945.   QueryInterface: function(iid) {
  1946.     if (!iid.equals(Components.interfaces.nsIUpdateManager) &&
  1947.         !iid.equals(Components.interfaces.nsISupports))
  1948.       throw Components.results.NS_ERROR_NO_INTERFACE;
  1949.     return this;
  1950.   }
  1951. };
  1952.  
  1953.  
  1954. /**
  1955.  * Checker
  1956.  * Checks for new Updates
  1957.  * @constructor
  1958.  */
  1959. function Checker() {
  1960. }
  1961. Checker.prototype = {
  1962.   /**
  1963.    * The XMLHttpRequest object that performs the connection.
  1964.    */
  1965.   _request  : null,
  1966.  
  1967.   /**
  1968.    * The nsIUpdateCheckListener callback
  1969.    */
  1970.   _callback : null,
  1971.  
  1972.   /**
  1973.    * The URL of the update service XML file to connect to that contains details
  1974.    * about available updates.
  1975.    */
  1976.   getUpdateURL: function(force) {
  1977.     this._forced = force;
  1978.  
  1979.     var defaults =
  1980.         gPref.QueryInterface(Components.interfaces.nsIPrefService).
  1981.         getDefaultBranch(null);
  1982.  
  1983.     // Use the override URL if specified.
  1984.     var url = getPref("getCharPref", PREF_APP_UPDATE_URL_OVERRIDE, null);
  1985.  
  1986.     // Otherwise, construct the update URL from component parts.
  1987.     if (!url) {
  1988.       try {
  1989.         url = defaults.getCharPref(PREF_APP_UPDATE_URL);
  1990.       } catch (e) {
  1991.       }
  1992.     }
  1993.  
  1994.     if (!url || url == "") {
  1995.       LOG("Checker", "Update URL not defined");
  1996.       return null;
  1997.     }
  1998.  
  1999.     url = url.replace(/%PRODUCT%/g, gApp.name);
  2000.     url = url.replace(/%VERSION%/g, gApp.version);
  2001.     url = url.replace(/%BUILD_ID%/g, gApp.appBuildID);
  2002.     url = url.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI);
  2003.     url = url.replace(/%OS_VERSION%/g, gOSVersion);
  2004.     url = url.replace(/%LOCALE%/g, getLocale());
  2005.     url = url.replace(/%CHANNEL%/g, getUpdateChannel());
  2006.     url = url.replace(/%PLATFORM_VERSION%/g, gApp.platformVersion);
  2007.     url = url.replace(/%DISTRIBUTION%/g,
  2008.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION));
  2009.     url = url.replace(/%DISTRIBUTION_VERSION%/g,
  2010.                       getDistributionPrefValue(PREF_APP_DISTRIBUTION_VERSION));
  2011.     url = url.replace(/\+/g, "%2B");
  2012.  
  2013.     if (force)
  2014.     url += "?force=1"
  2015.  
  2016.     LOG("Checker", "update url: " + url);
  2017.     return url;
  2018.   },
  2019.  
  2020.   /**
  2021.    * See nsIUpdateService.idl
  2022.    */
  2023.   checkForUpdates: function(listener, force) {
  2024.     if (!listener)
  2025.       throw Components.results.NS_ERROR_NULL_POINTER;
  2026.  
  2027.     if (!this.getUpdateURL(force) || (!this.enabled && !force))
  2028.       return;
  2029.  
  2030.     this._request =
  2031.       Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].
  2032.       createInstance(Components.interfaces.nsIXMLHttpRequest);
  2033.     this._request.open("GET", this.getUpdateURL(force), true);
  2034.     this._request.channel.notificationCallbacks = new BadCertHandler();
  2035.     this._request.overrideMimeType("text/xml");
  2036.     this._request.setRequestHeader("Cache-Control", "no-cache");
  2037.  
  2038.     var self = this;
  2039.     this._request.onerror     = function(event) { self.onError(event);    };
  2040.     this._request.onload      = function(event) { self.onLoad(event);     };
  2041.     this._request.onprogress  = function(event) { self.onProgress(event); };
  2042.  
  2043.     LOG("Checker", "checkForUpdates: sending request to " + this.getUpdateURL(force));
  2044.     this._request.send(null);
  2045.  
  2046.     this._callback = listener;
  2047.   },
  2048.  
  2049.   /**
  2050.    * When progress associated with the XMLHttpRequest is received.
  2051.    * @param   event
  2052.    *          The nsIDOMLSProgressEvent for the load.
  2053.    */
  2054.   onProgress: function(event) {
  2055.     LOG("Checker", "onProgress: " + event.position + "/" + event.totalSize);
  2056.     this._callback.onProgress(event.target, event.position, event.totalSize);
  2057.   },
  2058.  
  2059.   /**
  2060.    * Returns an array of nsIUpdate objects discovered by the update check.
  2061.    */
  2062.   get _updates() {
  2063.     var updatesElement = this._request.responseXML.documentElement;
  2064.     if (!updatesElement) {
  2065.       LOG("Checker", "get_updates: empty updates document?!");
  2066.       return [];
  2067.     }
  2068.  
  2069.     if (updatesElement.nodeName != "updates") {
  2070.       LOG("Checker", "get_updates: unexpected node name!");
  2071.       throw "";
  2072.     }
  2073.  
  2074.     var updates = [];
  2075.     for (var i = 0; i < updatesElement.childNodes.length; ++i) {
  2076.       var updateElement = updatesElement.childNodes.item(i);
  2077.       if (updateElement.nodeType != Node.ELEMENT_NODE ||
  2078.           updateElement.localName != "update")
  2079.         continue;
  2080.  
  2081.       updateElement.QueryInterface(Components.interfaces.nsIDOMElement);
  2082.       try {
  2083.         var update = new Update(updateElement);
  2084.       } catch (e) {
  2085.         LOG("Checker", "Invalid <update/>, ignoring...");
  2086.         continue;
  2087.       }
  2088.       update.serviceURL = this.getUpdateURL(this._forced);
  2089.       update.channel = getUpdateChannel();
  2090.       updates.push(update);
  2091.     }
  2092.  
  2093.     return updates;
  2094.   },
  2095.  
  2096.   /**
  2097.    * The XMLHttpRequest succeeded and the document was loaded.
  2098.    * @param   event
  2099.    *          The nsIDOMLSEvent for the load
  2100.    */
  2101.   onLoad: function(event) {
  2102.     LOG("Checker", "onLoad: request completed downloading document");
  2103.  
  2104.     try {
  2105.       checkCert(this._request.channel);
  2106.  
  2107.       // Analyze the resulting DOM and determine the set of updates to install
  2108.       var updates = this._updates;
  2109.  
  2110.       LOG("Checker", "Updates available: " + updates.length);
  2111.  
  2112.       // ... and tell the Update Service about what we discovered.
  2113.       this._callback.onCheckComplete(event.target, updates, updates.length);
  2114.     }
  2115.     catch (e) {
  2116.       LOG("Checker", "There was a problem with the update service URL specified, " +
  2117.           "either the XML file was malformed or it does not exist at the location " +
  2118.           "specified. Exception: " + e);
  2119.       var update = new Update(null);
  2120.       update.statusText = getStatusTextFromCode(404, 404);
  2121.       this._callback.onError(event.target, update);
  2122.     }
  2123.  
  2124.     this._request = null;
  2125.   },
  2126.  
  2127.   /**
  2128.    * There was an error of some kind during the XMLHttpRequest
  2129.    * @param   event
  2130.    *          The nsIDOMLSEvent for the load
  2131.    */
  2132.   onError: function(event) {
  2133.     LOG("Checker", "onError: error during load");
  2134.  
  2135.     var request = event.target;
  2136.     try {
  2137.       var status = request.status;
  2138.     }
  2139.     catch (e) {
  2140.       var req = request.channel.QueryInterface(Components.interfaces.nsIRequest);
  2141.       status = req.status;
  2142.     }
  2143.  
  2144.     // If we can't find an error string specific to this status code,
  2145.     // just use the 200 message from above, which means everything
  2146.     // "looks" fine but there was probably an XML error or a bogus file.
  2147.     var update = new Update(null);
  2148.     update.statusText = getStatusTextFromCode(status, 200);
  2149.     this._callback.onError(request, update);
  2150.  
  2151.     this._request = null;
  2152.   },
  2153.  
  2154.   /**
  2155.    * Whether or not we are allowed to do update checking.
  2156.    */
  2157.   _enabled: true,
  2158.  
  2159.   /**
  2160.    * See nsIUpdateService.idl
  2161.    */
  2162.   get enabled() {
  2163.     var aus =
  2164.         Components.classes["@mozilla.org/updates/update-service;1"].
  2165.         getService(Components.interfaces.nsIApplicationUpdateService);
  2166.     var enabled = getPref("getBoolPref", PREF_APP_UPDATE_ENABLED, true) &&
  2167.                   aus.canUpdate && this._enabled;
  2168.     return enabled;
  2169.   },
  2170.  
  2171.   /**
  2172.    * See nsIUpdateService.idl
  2173.    */
  2174.   stopChecking: function(duration) {
  2175.     // Always stop the current check
  2176.     if (this._request)
  2177.       this._request.abort();
  2178.  
  2179.     const nsIUpdateChecker = Components.interfaces.nsIUpdateChecker;
  2180.     switch (duration) {
  2181.     case nsIUpdateChecker.CURRENT_SESSION:
  2182.       this._enabled = false;
  2183.       break;
  2184.     case nsIUpdateChecker.ANY_CHECKS:
  2185.       this._enabled = false;
  2186.       gPref.setBoolPref(PREF_APP_UPDATE_ENABLED, this._enabled);
  2187.       break;
  2188.     }
  2189.   },
  2190.  
  2191.   /**
  2192.    * See nsISupports.idl
  2193.    */
  2194.   QueryInterface: function(iid) {
  2195.     if (!iid.equals(Components.interfaces.nsIUpdateChecker) &&
  2196.         !iid.equals(Components.interfaces.nsISupports))
  2197.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2198.     return this;
  2199.   }
  2200. };
  2201.  
  2202. /**
  2203.  * Manages the download of updates
  2204.  * @param   background
  2205.  *          Whether or not this downloader is operating in background
  2206.  *          update mode.
  2207.  * @constructor
  2208.  */
  2209. function Downloader(background) {
  2210.   this.background = background;
  2211. }
  2212. Downloader.prototype = {
  2213.   /**
  2214.    * The nsIUpdatePatch that we are downloading
  2215.    */
  2216.   _patch: null,
  2217.  
  2218.   /**
  2219.    * The nsIUpdate that we are downloading
  2220.    */
  2221.   _update: null,
  2222.  
  2223.   /**
  2224.    * The nsIIncrementalDownload object handling the download
  2225.    */
  2226.   _request: null,
  2227.  
  2228.   /**
  2229.    * Whether or not the update being downloaded is a complete replacement of
  2230.    * the user's existing installation or a patch representing the difference
  2231.    * between the new version and the previous version.
  2232.    */
  2233.   isCompleteUpdate: null,
  2234.  
  2235.   /**
  2236.    * Cancels the active download.
  2237.    */
  2238.   cancel: function() {
  2239.     if (this._request &&
  2240.         this._request instanceof Components.interfaces.nsIRequest) {
  2241.       const NS_BINDING_ABORTED = 0x804b0002;
  2242.       this._request.cancel(NS_BINDING_ABORTED);
  2243.     }
  2244.   },
  2245.  
  2246.   /**
  2247.    * Whether or not a patch has been downloaded and staged for installation.
  2248.    */
  2249.   get patchIsStaged() {
  2250.     return readStatusFile(getUpdatesDir()) == STATE_PENDING;
  2251.   },
  2252.  
  2253.   /**
  2254.    * Verify the downloaded file.  We assume that the download is complete at
  2255.    * this point.
  2256.    */
  2257.   _verifyDownload: function() {
  2258.     if (!this._request)
  2259.       return false;
  2260.  
  2261.     var destination = this._request.destination;
  2262.  
  2263.     // Ensure that the file size matches the expected file size.
  2264.     if (destination.fileSize != this._patch.size)
  2265.       return false;
  2266.  
  2267.     var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"].
  2268.         createInstance(nsIFileInputStream);
  2269.     fileStream.init(destination, MODE_RDONLY, PERMS_FILE, 0);
  2270.  
  2271.     try {
  2272.       var hash = Components.classes["@mozilla.org/security/hash;1"].
  2273.           createInstance(nsICryptoHash);
  2274.       var hashFunction = nsICryptoHash[this._patch.hashFunction.toUpperCase()];
  2275.       if (hashFunction == undefined)
  2276.         throw Components.results.NS_ERROR_UNEXPECTED;
  2277.       hash.init(hashFunction);
  2278.       hash.updateFromStream(fileStream, -1);
  2279.       // NOTE: For now, we assume that the format of _patch.hashValue is hex
  2280.       // encoded binary (such as what is typically output by programs like
  2281.       // sha1sum).  In the future, this may change to base64 depending on how
  2282.       // we choose to compute these hashes.
  2283.       digest = binaryToHex(hash.finish(false));
  2284.     } catch (e) {
  2285.       LOG("Downloader", "failed to compute hash of downloaded update archive");
  2286.       digest = "";
  2287.     }
  2288.  
  2289.     fileStream.close();
  2290.  
  2291.     return digest == this._patch.hashValue.toLowerCase();
  2292.   },
  2293.  
  2294.   /**
  2295.    * Select the patch to use given the current state of updateDir and the given
  2296.    * set of update patches.
  2297.    * @param   update
  2298.    *          A nsIUpdate object to select a patch from
  2299.    * @param   updateDir
  2300.    *          A nsIFile representing the update directory
  2301.    * @returns A nsIUpdatePatch object to download
  2302.    */
  2303.   _selectPatch: function(update, updateDir) {
  2304.     // Given an update to download, we will always try to download the patch
  2305.     // for a partial update over the patch for a full update.
  2306.  
  2307.     /**
  2308.      * Return the first UpdatePatch with the given type.
  2309.      * @param   type
  2310.      *          The type of the patch ("complete" or "partial")
  2311.      * @returns A nsIUpdatePatch object matching the type specified
  2312.      */
  2313.     function getPatchOfType(type) {
  2314.       for (var i = 0; i < update.patchCount; ++i) {
  2315.         var patch = update.getPatchAt(i);
  2316.         if (patch && patch.type == type)
  2317.           return patch;
  2318.       }
  2319.       return null;
  2320.     }
  2321.  
  2322.     // Look to see if any of the patches in the Update object has been
  2323.     // pre-selected for download, otherwise we must figure out which one
  2324.     // to select ourselves.
  2325.     var selectedPatch = update.selectedPatch;
  2326.  
  2327.     var state = readStatusFile(updateDir);
  2328.  
  2329.     // If this is a patch that we know about, then select it.  If it is a patch
  2330.     // that we do not know about, then remove it and use our default logic.
  2331.     var useComplete = false;
  2332.     if (selectedPatch) {
  2333.       LOG("Downloader", "found existing patch [state="+state+"]");
  2334.       switch (state) {
  2335.       case STATE_DOWNLOADING:
  2336.         LOG("Downloader", "resuming download");
  2337.         return selectedPatch;
  2338.       case STATE_PENDING:
  2339.         LOG("Downloader", "already downloaded and staged");
  2340.         return null;
  2341.       default:
  2342.         // Something went wrong when we tried to apply the previous patch.
  2343.         // Try the complete patch next time.
  2344.         if (update && selectedPatch.type == "partial") {
  2345.           useComplete = true;
  2346.         } else {
  2347.           // This is a pretty fatal error.  Just bail.
  2348.           LOG("Downloader", "failed to apply complete patch!");
  2349.           writeStatusFile(updateDir, STATE_NONE);
  2350.           return null;
  2351.         }
  2352.       }
  2353.  
  2354.       selectedPatch = null;
  2355.     }
  2356.  
  2357.     // If we were not able to discover an update from a previous download, we
  2358.     // select the best patch from the given set.
  2359.     var partialPatch = getPatchOfType("partial");
  2360.     if (!useComplete)
  2361.       selectedPatch = partialPatch;
  2362.     if (!selectedPatch) {
  2363.       if (partialPatch)
  2364.         partialPatch.selected = false;
  2365.       selectedPatch = getPatchOfType("complete");
  2366.     }
  2367.  
  2368.     // Restore the updateDir since we may have deleted it.
  2369.     updateDir = getUpdatesDir();
  2370.  
  2371.     // if update only contains a partial patch, selectedPatch == null here if
  2372.     // the partial patch has been attempted and fails and we're trying to get a
  2373.     // complete patch
  2374.     if (selectedPatch)
  2375.       selectedPatch.selected = true;
  2376.  
  2377.     update.isCompleteUpdate = useComplete;
  2378.  
  2379.     // Reset the Active Update object on the Update Manager and flush the
  2380.     // Active Update DB.
  2381.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2382.                        .getService(Components.interfaces.nsIUpdateManager);
  2383.     um.activeUpdate = update;
  2384.  
  2385.     return selectedPatch;
  2386.   },
  2387.  
  2388.   /**
  2389.    * Whether or not we are currently downloading something.
  2390.    */
  2391.   get isBusy() {
  2392.     return this._request != null;
  2393.   },
  2394.  
  2395.   /**
  2396.    * Download and stage the given update.
  2397.    * @param   update
  2398.    *          A nsIUpdate object to download a patch for. Cannot be null.
  2399.    */
  2400.   downloadUpdate: function(update) {
  2401.     if (!update)
  2402.       throw Components.results.NS_ERROR_NULL_POINTER;
  2403.  
  2404.     var updateDir = getUpdatesDir();
  2405.  
  2406.     this._update = update;
  2407.  
  2408.     // This function may return null, which indicates that there are no patches
  2409.     // to download.
  2410.     this._patch = this._selectPatch(update, updateDir);
  2411.     if (!this._patch) {
  2412.       LOG("Downloader", "no patch to download");
  2413.       return readStatusFile(updateDir);
  2414.     }
  2415.     this.isCompleteUpdate = this._patch.type == "complete";
  2416.  
  2417.     var patchFile = updateDir.clone();
  2418.     patchFile.append(FILE_UPDATE_ARCHIVE);
  2419.  
  2420.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  2421.         getService(Components.interfaces.nsIIOService);
  2422.     var uri = ios.newURI(this._patch.URL, null, null);
  2423.  
  2424.     this._request =
  2425.         Components.classes["@mozilla.org/network/incremental-download;1"].
  2426.         createInstance(nsIIncrementalDownload);
  2427.  
  2428.     LOG("Downloader", "downloadUpdate: Downloading from " + uri.spec + " to " +
  2429.         patchFile.path);
  2430.  
  2431.     var interval = this.background ? DOWNLOAD_BACKGROUND_INTERVAL
  2432.                                    : DOWNLOAD_FOREGROUND_INTERVAL;
  2433.     this._request.init(uri, patchFile, DOWNLOAD_CHUNK_SIZE, interval);
  2434.     this._request.start(this, null);
  2435.  
  2436.     writeStatusFile(updateDir, STATE_DOWNLOADING);
  2437.     this._patch.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2438.     this._patch.state = STATE_DOWNLOADING;
  2439.     var um = Components.classes["@mozilla.org/updates/update-manager;1"]
  2440.                        .getService(Components.interfaces.nsIUpdateManager);
  2441.     um.saveUpdates();
  2442.     return STATE_DOWNLOADING;
  2443.   },
  2444.  
  2445.   /**
  2446.    * An array of download listeners to notify when we receive
  2447.    * nsIRequestObserver or nsIProgressEventSink method calls.
  2448.    */
  2449.   _listeners: [],
  2450.  
  2451.   /**
  2452.    * Adds a listener to the download process
  2453.    * @param   listener
  2454.    *          A download listener, implementing nsIRequestObserver and
  2455.    *          nsIProgressEventSink
  2456.    */
  2457.   addDownloadListener: function(listener) {
  2458.     for (var i = 0; i < this._listeners.length; ++i) {
  2459.       if (this._listeners[i] == listener)
  2460.         return;
  2461.     }
  2462.     this._listeners.push(listener);
  2463.   },
  2464.  
  2465.   /**
  2466.    * Removes a download listener
  2467.    * @param   listener
  2468.    *          The listener to remove.
  2469.    */
  2470.   removeDownloadListener: function(listener) {
  2471.     for (var i = 0; i < this._listeners.length; ++i) {
  2472.       if (this._listeners[i] == listener) {
  2473.         this._listeners.splice(i, 1);
  2474.         return;
  2475.       }
  2476.     }
  2477.   },
  2478.  
  2479.   /**
  2480.    * When the async request begins
  2481.    * @param   request
  2482.    *          The nsIRequest object for the transfer
  2483.    * @param   context
  2484.    *          Additional data
  2485.    */
  2486.   onStartRequest: function(request, context) {
  2487.     request.QueryInterface(nsIIncrementalDownload);
  2488.     LOG("Downloader", "onStartRequest: " + request.URI.spec);
  2489.  
  2490.     var listenerCount = this._listeners.length;
  2491.     for (var i = 0; i < listenerCount; ++i)
  2492.       this._listeners[i].onStartRequest(request, context);
  2493.   },
  2494.  
  2495.   /**
  2496.    * When new data has been downloaded
  2497.    * @param   request
  2498.    *          The nsIRequest object for the transfer
  2499.    * @param   context
  2500.    *          Additional data
  2501.    * @param   progress
  2502.    *          The current number of bytes transferred
  2503.    * @param   maxProgress
  2504.    *          The total number of bytes that must be transferred
  2505.    */
  2506.   onProgress: function(request, context, progress, maxProgress) {
  2507.     request.QueryInterface(nsIIncrementalDownload);
  2508.     LOG("Downloader.onProgress", "onProgress: " + request.URI.spec + ", " + progress + "/" + maxProgress);
  2509.  
  2510.     var listenerCount = this._listeners.length;
  2511.     for (var i = 0; i < listenerCount; ++i) {
  2512.       var listener = this._listeners[i];
  2513.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2514.         listener.onProgress(request, context, progress, maxProgress);
  2515.     }
  2516.   },
  2517.  
  2518.   /**
  2519.    * When we have new status text
  2520.    * @param   request
  2521.    *          The nsIRequest object for the transfer
  2522.    * @param   context
  2523.    *          Additional data
  2524.    * @param   status
  2525.    *          A status code
  2526.    * @param   statusText
  2527.    *          Human readable version of |status|
  2528.    */
  2529.   onStatus: function(request, context, status, statusText) {
  2530.     request.QueryInterface(nsIIncrementalDownload);
  2531.     LOG("Downloader", "onStatus: " + request.URI.spec + " status = " + status + ", text = " + statusText);
  2532.     var listenerCount = this._listeners.length;
  2533.     for (var i = 0; i < listenerCount; ++i) {
  2534.       var listener = this._listeners[i];
  2535.       if (listener instanceof Components.interfaces.nsIProgressEventSink)
  2536.         listener.onStatus(request, context, status, statusText);
  2537.     }
  2538.   },
  2539.  
  2540.   /**
  2541.    * When data transfer ceases
  2542.    * @param   request
  2543.    *          The nsIRequest object for the transfer
  2544.    * @param   context
  2545.    *          Additional data
  2546.    * @param   status
  2547.    *          Status code containing the reason for the cessation.
  2548.    */
  2549.   onStopRequest: function(request, context, status) {
  2550.     request.QueryInterface(nsIIncrementalDownload);
  2551.     LOG("Downloader", "onStopRequest: " + request.URI.spec + ", status = " + status);
  2552.  
  2553.     var state = this._patch.state;
  2554.     var shouldShowPrompt = false;
  2555.     var deleteActiveUpdate = false;
  2556.     const NS_BINDING_ABORTED = 0x804b0002;
  2557.     const NS_ERROR_ABORT = 0x80004004;
  2558.     if (Components.isSuccessCode(status)) {
  2559.       var sbs =
  2560.           Components.classes["@mozilla.org/intl/stringbundle;1"].
  2561.           getService(Components.interfaces.nsIStringBundleService);
  2562.       var updateStrings = sbs.createBundle(URI_UPDATES_PROPERTIES);
  2563.       if (this._verifyDownload()) {
  2564.         state = STATE_PENDING;
  2565.  
  2566.         // We only need to explicitly show the prompt if this is a backround
  2567.         // download, since otherwise some kind of UI is already visible and
  2568.         // that UI will notify.
  2569.         if (this.background)
  2570.           shouldShowPrompt = true;
  2571.  
  2572.         // Tell the updater.exe we're ready to apply.
  2573.         writeStatusFile(getUpdatesDir(), state);
  2574.         this._update.installDate = (new Date()).getTime();
  2575.         this._update.statusText = updateStrings.
  2576.           GetStringFromName("installPending");
  2577.       } else {
  2578.         LOG("Downloader", "onStopRequest: download verification failed");
  2579.         state = STATE_DOWNLOAD_FAILED;
  2580.  
  2581.         var brandStrings = sbs.createBundle(URI_BRAND_PROPERTIES);
  2582.         var brandShortName = brandStrings.GetStringFromName("brandShortName");
  2583.         this._update.statusText = updateStrings.
  2584.           formatStringFromName("verificationError", [brandShortName], 1);
  2585.  
  2586.         // TODO: use more informative error code here
  2587.         status = Components.results.NS_ERROR_UNEXPECTED;
  2588.  
  2589.         var message = getStatusTextFromCode("verification_failed",
  2590.           "verification_failed");
  2591.         this._update.statusText = message;
  2592.  
  2593.         if (this._update.isCompleteUpdate)
  2594.           deleteActiveUpdate = true;
  2595.  
  2596.         // Destroy the updates directory, since we're done with it.
  2597.         cleanUpUpdatesDir();
  2598.       }
  2599.     }
  2600.     else if (status != NS_BINDING_ABORTED &&
  2601.              status != NS_ERROR_ABORT) {
  2602.       LOG("Downloader", "onStopRequest: Non-verification failure");
  2603.       // Some sort of other failure, log this in the |statusText| property
  2604.       state = STATE_DOWNLOAD_FAILED;
  2605.  
  2606.       // XXXben - if |request| (The Incremental Download) provided a means
  2607.       // for accessing the http channel we could do more here.
  2608.  
  2609.       const NS_BINDING_FAILED = 2152398849;
  2610.       this._update.statusText = getStatusTextFromCode(status,
  2611.         NS_BINDING_FAILED);
  2612.  
  2613.       // Destroy the updates directory, since we're done with it.
  2614.       cleanUpUpdatesDir();
  2615.  
  2616.       deleteActiveUpdate = true;
  2617.     }
  2618.     LOG("Downloader", "Setting state to: " + state);
  2619.     this._patch.state = state;
  2620.     var um =
  2621.         Components.classes["@mozilla.org/updates/update-manager;1"].
  2622.         getService(Components.interfaces.nsIUpdateManager);
  2623.     if (deleteActiveUpdate) {
  2624.       this._update.installDate = (new Date()).getTime();
  2625.       um.activeUpdate = null;
  2626.     }
  2627.     um.saveUpdates();
  2628.  
  2629.     var listenerCount = this._listeners.length;
  2630.     for (var i = 0; i < listenerCount; ++i)
  2631.       this._listeners[i].onStopRequest(request, context, status);
  2632.  
  2633.     this._request = null;
  2634.  
  2635.     if (state == STATE_DOWNLOAD_FAILED) {
  2636.       if (!this._update.isCompleteUpdate) {
  2637.         var allFailed = true;
  2638.  
  2639.         // If we were downloading a patch and the patch verification phase
  2640.         // failed, log this and then commence downloading the complete update.
  2641.         LOG("Downloader", "onStopRequest: Verification of patch failed, downloading complete update");
  2642.         this._update.isCompleteUpdate = true;
  2643.         var status = this.downloadUpdate(this._update);
  2644.  
  2645.         if (status == STATE_NONE) {
  2646.           cleanupActiveUpdate();
  2647.         } else {
  2648.           allFailed = false;
  2649.         }
  2650.         // This will reset the |.state| property on this._update if a new
  2651.         // download initiates.
  2652.       }
  2653.  
  2654.       // if we still fail after trying a complete download, give up completely
  2655.       if (allFailed) {
  2656.         // In all other failure cases, i.e. we're S.O.L. - no more failing over
  2657.         // ...
  2658.  
  2659.         // If this was ever a foreground download, and now there is no UI active
  2660.         // (e.g. because the user closed the download window) and there was an
  2661.         // error, we must notify now. Otherwise we can keep the failure to
  2662.         // ourselves since the user won't be expecting it.
  2663.         try {
  2664.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2665.           var fgdl = this._update.getProperty("foregroundDownload");
  2666.         }
  2667.         catch (e) {
  2668.         }
  2669.  
  2670.         if (fgdl == "true") {
  2671.           var prompter =
  2672.               Components.classes["@mozilla.org/updates/update-prompt;1"].
  2673.               createInstance(Components.interfaces.nsIUpdatePrompt);
  2674.           this._update.QueryInterface(Components.interfaces.nsIWritablePropertyBag);
  2675.           this._update.setProperty("downloadFailed", "true");
  2676.           prompter.showUpdateError(this._update);
  2677.         }
  2678.       }
  2679.  
  2680.       // the complete download succeeded or total failure was handled, so exit
  2681.       return;
  2682.     }
  2683.  
  2684.     // Do this after *everything* else, since it will likely cause the app
  2685.     // to shut down.
  2686.     if (shouldShowPrompt) {
  2687.       // Notify the user that an update has been downloaded and is ready for
  2688.       // installation (i.e. that they should restart the application). We do
  2689.       // not notify on failed update attempts.
  2690.       var prompter =
  2691.           Components.classes["@mozilla.org/updates/update-prompt;1"].
  2692.           createInstance(Components.interfaces.nsIUpdatePrompt);
  2693.       prompter.showUpdateDownloaded(this._update, true);
  2694.     }
  2695.   },
  2696.  
  2697.   /**
  2698.    * See nsIInterfaceRequestor.idl
  2699.    */
  2700.   getInterface: function(iid) {
  2701.     // The network request may require proxy authentication, so provide the
  2702.     // default nsIAuthPrompt if requested.
  2703.     if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  2704.       var prompt =
  2705.           Components.classes["@mozilla.org/network/default-auth-prompt;1"].
  2706.           createInstance();
  2707.       return prompt.QueryInterface(iid);
  2708.     }
  2709.     throw Components.results.NS_ERROR_NO_INTERFACE;
  2710.   },
  2711.  
  2712.   /**
  2713.    * See nsISupports.idl
  2714.    */
  2715.   QueryInterface: function(iid) {
  2716.     if (!iid.equals(Components.interfaces.nsIRequestObserver) &&
  2717.         !iid.equals(Components.interfaces.nsIProgressEventSink) &&
  2718.         !iid.equals(Components.interfaces.nsIInterfaceRequestor) &&
  2719.         !iid.equals(Components.interfaces.nsISupports))
  2720.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2721.     return this;
  2722.   }
  2723. };
  2724.  
  2725. /**
  2726.  * A manager for update check timers. Manages timers that fire over long
  2727.  * periods of time (e.g. days, weeks).
  2728.  * @constructor
  2729.  */
  2730. function TimerManager() {
  2731.   getObserverService().addObserver(this, "xpcom-shutdown", false);
  2732.  
  2733.   const nsITimer = Components.interfaces.nsITimer;
  2734.   this._timer = Components.classes["@mozilla.org/timer;1"]
  2735.                           .createInstance(nsITimer);
  2736.   var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2737.   this._timer.initWithCallback(this, timerInterval,
  2738.                                nsITimer.TYPE_REPEATING_SLACK);
  2739. }
  2740. TimerManager.prototype = {
  2741.   /**
  2742.    * See nsIObserver.idl
  2743.    */
  2744.   observe: function(subject, topic, data) {
  2745.     if (topic == "xpcom-shutdown") {
  2746.      getObserverService().removeObserver(this, "xpcom-shutdown");
  2747.  
  2748.       // Release everything we hold onto.
  2749.       for (var timerID in this._timers)
  2750.         delete this._timers[timerID];
  2751.       this._timer = null;
  2752.       this._timers = null;
  2753.     }
  2754.   },
  2755.  
  2756.   /**
  2757.    * The Checker Timer
  2758.    */
  2759.   _timer: null,
  2760.  
  2761.   /**
  2762.    * The set of registered timers.
  2763.    */
  2764.   _timers: { },
  2765.  
  2766.   /**
  2767.    * Called when the checking timer fires.
  2768.    * @param   timer
  2769.    *          The checking timer that fired.
  2770.    */
  2771.   notify: function(timer) {
  2772.     for (var timerID in this._timers) {
  2773.       var timerData = this._timers[timerID];
  2774.       var lastUpdateTime = timerData.lastUpdateTime;
  2775.       var now = Math.round(Date.now() / 1000);
  2776.  
  2777.       // Fudge the lastUpdateTime by some random increment of the update
  2778.       // check interval (e.g. some random slice of 10 minutes) so that when
  2779.       // the time comes to check, we offset each client request by a random
  2780.       // amount so they don't all hit at once. app.update.timer is in milliseconds,
  2781.       // whereas app.update.lastUpdateTime is in seconds
  2782.       var timerInterval = getPref("getIntPref", PREF_APP_UPDATE_TIMER, 600000);
  2783.       lastUpdateTime += Math.round(Math.random() * timerInterval / 1000);
  2784.  
  2785.       if ((now - lastUpdateTime) > timerData.interval &&
  2786.           timerData.callback instanceof Components.interfaces.nsITimerCallback) {
  2787.         timerData.callback.notify(timer);
  2788.         timerData.lastUpdateTime = now;
  2789.         var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, timerID);
  2790.         gPref.setIntPref(preference, now);
  2791.       }
  2792.     }
  2793.   },
  2794.  
  2795.   /**
  2796.    * See nsIUpdateService.idl
  2797.    */
  2798.   registerTimer: function(id, callback, interval) {
  2799.     var preference = PREF_APP_UPDATE_LASTUPDATETIME_FMT.replace(/%ID%/, id);
  2800.     var now = Math.round(Date.now() / 1000);
  2801.     var lastUpdateTime = null;
  2802.     if (gPref.prefHasUserValue(preference)) {
  2803.       lastUpdateTime = gPref.getIntPref(preference);
  2804.     } else {
  2805.       gPref.setIntPref(preference, now);
  2806.       lastUpdateTime = now;
  2807.     }
  2808.     this._timers[id] = { callback       : callback,
  2809.                          interval       : interval,
  2810.                          lastUpdateTime : lastUpdateTime };
  2811.   },
  2812.  
  2813.   /**
  2814.    * See nsISupports.idl
  2815.    */
  2816.   QueryInterface: function(iid) {
  2817.     if (!iid.equals(Components.interfaces.nsIUpdateTimerManager) &&
  2818.         !iid.equals(Components.interfaces.nsITimerCallback) &&
  2819.         !iid.equals(Components.interfaces.nsIObserver) &&
  2820.         !iid.equals(Components.interfaces.nsISupports))
  2821.       throw Components.results.NS_ERROR_NO_INTERFACE;
  2822.     return this;
  2823.   }
  2824. };
  2825.  
  2826. //@line 2817 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  2827. /**
  2828.  * UpdatePrompt
  2829.  * An object which can prompt the user with information about updates, request
  2830.  * action, etc. Embedding clients can override this component with one that
  2831.  * invokes a native front end.
  2832.  * @constructor
  2833.  */
  2834. function UpdatePrompt() {
  2835. }
  2836. UpdatePrompt.prototype = {
  2837.   /**
  2838.    * See nsIUpdateService.idl
  2839.    */
  2840.   checkForUpdates: function() {
  2841.     this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2842.                  null, null);
  2843.   },
  2844.  
  2845.   /**
  2846.    * See nsIUpdateService.idl
  2847.    */
  2848.   showUpdateAvailable: function(update) {
  2849.     if (!this._enabled)
  2850.       return;
  2851.     var bundle = this._updateBundle;
  2852.     var stringsPrefix = "updateAvailable_" + update.type + ".";
  2853.     var title = bundle.formatStringFromName(stringsPrefix + "title", [update.name], 1);
  2854.     var text = bundle.GetStringFromName(stringsPrefix + "text");
  2855.     var imageUrl = "";
  2856.     this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2857.                            "Update:Wizard", "updatesavailable", update,
  2858.                            title, text, imageUrl);
  2859.   },
  2860.  
  2861.   /**
  2862.    * See nsIUpdateService.idl
  2863.    */
  2864.   showUpdateDownloaded: function(update, background) {
  2865.     if (background) {
  2866.       if (!this._enabled)
  2867.         return;
  2868.       var bundle = this._updateBundle;
  2869.       var stringsPrefix = "updateDownloaded_" + update.type + ".";
  2870.       var title = bundle.formatStringFromName(stringsPrefix + "title", [update.name], 1);
  2871.       var text = bundle.GetStringFromName(stringsPrefix + "text");
  2872.       var imageUrl = "";
  2873.       this._showUnobtrusiveUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2874.                               "Update:Wizard", "finishedBackground", update,
  2875.                               title, text, imageUrl);
  2876.     } else {
  2877.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null,
  2878.                    "Update:Wizard", "finishedBackground", update);
  2879.     }
  2880.   },
  2881.  
  2882.   /**
  2883.    * See nsIUpdateService.idl
  2884.    */
  2885.   showUpdateInstalled: function(update) {
  2886.     var showUpdateInstalledUI = getPref("getBoolPref",
  2887.       PREF_APP_UPDATE_SHOW_INSTALLED_UI, true);
  2888.     if (this._enabled && showUpdateInstalledUI) {
  2889.       this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2890.                    "installed", update);
  2891.     }
  2892.   },
  2893.  
  2894.   /**
  2895.    * See nsIUpdateService.idl
  2896.    */
  2897.   showUpdateError: function(update) {
  2898.     if (this._enabled) {
  2899.       // In some cases, we want to just show a simple alert dialog:
  2900.       if (update.state == STATE_FAILED && update.errorCode == WRITE_ERROR) {
  2901.         var updateBundle = this._updateBundle;
  2902.         var title = updateBundle.GetStringFromName("updaterIOErrorTitle");
  2903.         var text = updateBundle.formatStringFromName("updaterIOErrorMsg",
  2904.                                                      [gApp.name, gApp.name], 2);
  2905.         var ww =
  2906.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
  2907.             getService(Components.interfaces.nsIWindowWatcher);
  2908.         ww.getNewPrompter(null).alert(title, text);
  2909.       } else {
  2910.         this._showUI(null, URI_UPDATE_PROMPT_DIALOG, null, "Update:Wizard",
  2911.                      "errors", update);
  2912.       }
  2913.     }
  2914.   },
  2915.  
  2916.   /**
  2917.    * See nsIUpdateService.idl
  2918.    */
  2919.   showUpdateHistory: function(parent) {
  2920.     this._showUI(parent, URI_UPDATE_HISTORY_DIALOG, "modal,dialog=yes", "Update:History",
  2921.                  null, null);
  2922.   },
  2923.  
  2924.   /**
  2925.    * Whether or not we are enabled (i.e. not in Silent mode)
  2926.    */
  2927.   get _enabled() {
  2928.     return !getPref("getBoolPref", PREF_APP_UPDATE_SILENT, false);
  2929.   },
  2930.  
  2931.   get _updateBundle() {
  2932.     return Components.classes["@mozilla.org/intl/stringbundle;1"]
  2933.                      .getService(Components.interfaces.nsIStringBundleService)
  2934.                      .createBundle(URI_UPDATES_PROPERTIES);
  2935.   },
  2936.  
  2937.   /**
  2938.    * Initiate a less obtrusive UI, starting with a non-modal notification alert
  2939.    * @param   parent
  2940.    *          A parent window, can be null
  2941.    * @param   uri
  2942.    *          The URI string of the dialog to show
  2943.    * @param   name
  2944.    *          The Window Name of the dialog to show, in case it is already open
  2945.    *          and can merely be focused
  2946.    * @param   page
  2947.    *          The page of the wizard to be displayed, if one is already open.
  2948.    * @param   update
  2949.    *          An update to pass to the UI in the window arguments.
  2950.    *          Can be null
  2951.    * @param   title
  2952.    *          The title for the notification alert.
  2953.    * @param   text
  2954.    *          The contents of the notification alert.
  2955.    * @param   imageUrl
  2956.    *          A URL identifying the image to put in the notification alert.
  2957.    */
  2958.   _showUnobtrusiveUI: function(parent, uri, features, name, page, update,
  2959.                                title, text, imageUrl) {
  2960.     var observer = {
  2961.       updatePrompt: this,
  2962.       service: null,
  2963.       timer: null,
  2964.       notify: function () {
  2965.         // the user hasn't restarted yet => prompt when idle
  2966.         this.service.removeObserver(this, "quit-application");
  2967.         this.updatePrompt._showUIWhenIdle(parent, uri, features, name, page, update);
  2968.       },
  2969.       observe: function (aSubject, aTopic, aData) {
  2970.         switch (aTopic) {
  2971.           case "alertclickcallback":
  2972.             this.updatePrompt._showUI(parent, uri, features, name, page, update);
  2973.             // fall thru
  2974.           case "quit-application":
  2975.             this.timer.cancel();
  2976.             this.service.removeObserver(this, "quit-application");
  2977.             break;
  2978.         }
  2979.       }
  2980.     };
  2981.  
  2982.     try {
  2983.       var notifier = Components.classes["@mozilla.org/alerts-service;1"]
  2984.                                .getService(Components.interfaces.nsIAlertsService);
  2985.       notifier.showAlertNotification(imageUrl, title, text, true, "", observer);
  2986.     }
  2987.     catch (e) {
  2988.       // Failed to retrieve alerts service, platform unsupported
  2989.       this._showUIWhenIdle(parent, uri, features, name, page, update);
  2990.       return;
  2991.     }
  2992.  
  2993.     observer.service =
  2994.       Components.classes["@mozilla.org/observer-service;1"]
  2995.                 .getService(Components.interfaces.nsIObserverService);
  2996.     observer.service.addObserver(observer, "quit-application", false);
  2997.  
  2998.     // Give the user x seconds to react before showing the big UI
  2999.     var promptWaitTime = getPref("getIntPref", PREF_APP_UPDATE_PROMPTWAITTIME, 43200);
  3000.     observer.timer =
  3001.       Components.classes["@mozilla.org/timer;1"]
  3002.                 .createInstance(Components.interfaces.nsITimer);
  3003.     observer.timer.initWithCallback(observer, promptWaitTime * 1000,
  3004.                                     observer.timer.TYPE_ONE_SHOT);
  3005.   },
  3006.  
  3007.   /**
  3008.    * Show the UI when the user was idle
  3009.    * @param   parent
  3010.    *          A parent window, can be null
  3011.    * @param   uri
  3012.    *          The URI string of the dialog to show
  3013.    * @param   name
  3014.    *          The Window Name of the dialog to show, in case it is already open
  3015.    *          and can merely be focused
  3016.    * @param   page
  3017.    *          The page of the wizard to be displayed, if one is already open.
  3018.    * @param   update
  3019.    *          An update to pass to the UI in the window arguments.
  3020.    *          Can be null
  3021.    */
  3022.   _showUIWhenIdle: function(parent, uri, features, name, page, update) {
  3023.     var idleService =
  3024.       Components.classes["@mozilla.org/widget/idleservice;1"]
  3025.                 .getService(Components.interfaces.nsIIdleService);
  3026.  
  3027.     const IDLE_TIME = getPref("getIntPref", PREF_APP_UPDATE_IDLETIME, 60);
  3028.     if (idleService.idleTime / 1000 >= IDLE_TIME) {
  3029.       this._showUI(parent, uri, features, name, page, update);
  3030.     } else {
  3031.       var observerService =
  3032.         Components.classes["@mozilla.org/observer-service;1"]
  3033.                   .getService(Components.interfaces.nsIObserverService);
  3034.       var observer = {
  3035.         updatePrompt: this,
  3036.         observe: function (aSubject, aTopic, aData) {
  3037.           switch (aTopic) {
  3038.             case "idle":
  3039.               this.updatePrompt._showUI(parent, uri, features, name, page, update);
  3040.               // fall thru
  3041.             case "quit-application":
  3042.               idleService.removeIdleObserver(this, IDLE_TIME);
  3043.               observerService.removeObserver(this, "quit-application");
  3044.               break;
  3045.           }
  3046.         }
  3047.       };
  3048.       idleService.addIdleObserver(observer, IDLE_TIME);
  3049.       observerService.addObserver(observer, "quit-application", false);
  3050.     }
  3051.   },
  3052.  
  3053.   /**
  3054.    * Show the Update Checking UI
  3055.    * @param   parent
  3056.    *          A parent window, can be null
  3057.    * @param   uri
  3058.    *          The URI string of the dialog to show
  3059.    * @param   name
  3060.    *          The Window Name of the dialog to show, in case it is already open
  3061.    *          and can merely be focused
  3062.    * @param   page
  3063.    *          The page of the wizard to be displayed, if one is already open.
  3064.    * @param   update
  3065.    *          An update to pass to the UI in the window arguments.
  3066.    *          Can be null
  3067.    */
  3068.   _showUI: function(parent, uri, features, name, page, update) {
  3069.     var ary = null;
  3070.     if (update) {
  3071.       ary = Components.classes["@mozilla.org/supports-array;1"]
  3072.                       .createInstance(Components.interfaces.nsISupportsArray);
  3073.       ary.AppendElement(update);
  3074.     }
  3075.  
  3076.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  3077.                        .getService(Components.interfaces.nsIWindowMediator);
  3078.     var win = wm.getMostRecentWindow(name);
  3079.     if (win) {
  3080.       if (page && "setCurrentPage" in win)
  3081.         win.setCurrentPage(page);
  3082.       win.focus();
  3083.     }
  3084.     else {
  3085.       var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no";
  3086.       if (features)
  3087.         openFeatures += "," + features;
  3088.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  3089.                          .getService(Components.interfaces.nsIWindowWatcher);
  3090.       ww.openWindow(parent, uri, "", openFeatures, ary);
  3091.     }
  3092.   },
  3093.  
  3094.   /**
  3095.    * See nsISupports.idl
  3096.    */
  3097.   QueryInterface: function(iid) {
  3098.     if (!iid.equals(Components.interfaces.nsIUpdatePrompt) &&
  3099.         !iid.equals(Components.interfaces.nsISupports))
  3100.       throw Components.results.NS_ERROR_NO_INTERFACE;
  3101.     return this;
  3102.   }
  3103. };
  3104. //@line 3095 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  3105.  
  3106. var gModule = {
  3107.   registerSelf: function(componentManager, fileSpec, location, type) {
  3108.     componentManager = componentManager.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  3109.  
  3110.     for (var key in this._objects) {
  3111.       var obj = this._objects[key];
  3112.       componentManager.registerFactoryLocation(obj.CID, obj.className, obj.contractID,
  3113.                                                fileSpec, location, type);
  3114.     }
  3115.  
  3116.     // Make the Update Service a startup observer
  3117.     var categoryManager = Components.classes["@mozilla.org/categorymanager;1"]
  3118.                                     .getService(Components.interfaces.nsICategoryManager);
  3119.     categoryManager.addCategoryEntry("app-startup", this._objects.service.className,
  3120.                                      "service," + this._objects.service.contractID,
  3121.                                      true, true);
  3122.   },
  3123.  
  3124.   getClassObject: function(componentManager, cid, iid) {
  3125.     if (!iid.equals(Components.interfaces.nsIFactory))
  3126.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  3127.  
  3128.     for (var key in this._objects) {
  3129.       if (cid.equals(this._objects[key].CID))
  3130.         return this._objects[key].factory;
  3131.     }
  3132.  
  3133.     throw Components.results.NS_ERROR_NO_INTERFACE;
  3134.   },
  3135.  
  3136.   _objects: {
  3137.     service: { CID        : Components.ID("{B3C290A6-3943-4B89-8BBE-C01EB7B3B311}"),
  3138.                contractID : "@mozilla.org/updates/update-service;1",
  3139.                className  : "Update Service",
  3140.                factory    : makeFactory(UpdateService)
  3141.              },
  3142.     checker: { CID        : Components.ID("{898CDC9B-E43F-422F-9CC4-2F6291B415A3}"),
  3143.                contractID : "@mozilla.org/updates/update-checker;1",
  3144.                className  : "Update Checker",
  3145.                factory    : makeFactory(Checker)
  3146.              },
  3147. //@line 3138 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  3148.     prompt:  { CID        : Components.ID("{27ABA825-35B5-4018-9FDD-F99250A0E722}"),
  3149.                contractID : "@mozilla.org/updates/update-prompt;1",
  3150.                className  : "Update Prompt",
  3151.                factory    : makeFactory(UpdatePrompt)
  3152.              },
  3153. //@line 3144 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  3154.     timers:  { CID        : Components.ID("{B322A5C0-A419-484E-96BA-D7182163899F}"),
  3155.                contractID : "@mozilla.org/updates/timer-manager;1",
  3156.                className  : "Timer Manager",
  3157.                factory    : makeFactory(TimerManager)
  3158.              },
  3159.     manager: { CID        : Components.ID("{093C2356-4843-4C65-8709-D7DBCBBE7DFB}"),
  3160.                contractID : "@mozilla.org/updates/update-manager;1",
  3161.                className  : "Update Manager",
  3162.                factory    : makeFactory(UpdateManager)
  3163.              },
  3164.   },
  3165.  
  3166.   canUnload: function(componentManager) {
  3167.     return true;
  3168.   }
  3169. };
  3170.  
  3171. /**
  3172.  * Creates a factory for instances of an object created using the passed-in
  3173.  * constructor.
  3174.  */
  3175. function makeFactory(ctor) {
  3176.   function ci(outer, iid) {
  3177.     if (outer != null)
  3178.       throw Components.results.NS_ERROR_NO_AGGREGATION;
  3179.     return (new ctor()).QueryInterface(iid);
  3180.   }
  3181.   return { createInstance: ci };
  3182. }
  3183.  
  3184. function NSGetModule(compMgr, fileSpec) {
  3185.   return gModule;
  3186. }
  3187.  
  3188. /**
  3189.  * Determines whether or there are installed addons which are incompatible
  3190.  * with this update.
  3191.  * @param   update
  3192.  *          The update to check compatibility against
  3193.  * @returns true if there are no addons installed that are incompatible with
  3194.  *          the specified update, false otherwise.
  3195.  */
  3196. function isCompatible(update) {
  3197. //@line 3188 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  3198.   var em =
  3199.       Components.classes["@mozilla.org/extensions/manager;1"].
  3200.       getService(nsIExtensionManager);
  3201.   var items = em.getIncompatibleItemList("", update.extensionVersion,
  3202.     update.platformVersion, nsIUpdateItem.TYPE_ANY, false, { });
  3203.   return items.length == 0;
  3204. //@line 3197 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  3205. }
  3206.  
  3207. /**
  3208.  * Shows a prompt for an update, provided there are no incompatible addons.
  3209.  * If there are, kick off an update check and see if updates are available
  3210.  * that will resolve the incompatibilities.
  3211.  * @param   update
  3212.  *          The available update to show
  3213.  */
  3214. function showPromptIfNoIncompatibilities(update) {
  3215.   function showPrompt(update) {
  3216.     LOG("UpdateService", "_selectAndInstallUpdate: need to prompt user before continuing...");
  3217.     var prompter =
  3218.         Components.classes["@mozilla.org/updates/update-prompt;1"].
  3219.         createInstance(Components.interfaces.nsIUpdatePrompt);
  3220.     prompter.showUpdateAvailable(update);
  3221.   }
  3222.  
  3223. //@line 3216 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  3224.   /**
  3225.    * Determines if an addon is compatible with a particular update.
  3226.    * @param   addon
  3227.    *          The addon to check
  3228.    * @param   version
  3229.    *          The extensionVersion of the update to check for compatibility
  3230.    *          against.
  3231.    * @returns true if the addon is compatible, false otherwise
  3232.    */
  3233.   function addonIsCompatible(addon, version) {
  3234.     var vc =
  3235.         Components.classes["@mozilla.org/xpcom/version-comparator;1"].
  3236.         getService(Components.interfaces.nsIVersionComparator);
  3237.     return (vc.compare(version, addon.minAppVersion) >= 0) &&
  3238.            (vc.compare(version, addon.maxAppVersion) <= 0);
  3239.   }
  3240.  
  3241.   /**
  3242.    * An object implementing nsIAddonUpdateCheckListener that looks for
  3243.    * available updates to addons and if updates are found that will make the
  3244.    * user's installed addon set compatible with the update, suppresses the
  3245.    * prompt that would otherwise be shown.
  3246.    * @param   addons
  3247.    *          An array of incompatible addons that are installed.
  3248.    * @constructor
  3249.    */
  3250.   function Listener(addons) {
  3251.     this._addons = addons;
  3252.   }
  3253.   Listener.prototype = {
  3254.     _addons: null,
  3255.  
  3256.     /**
  3257.      * See nsIUpdateService.idl
  3258.      */
  3259.     onUpdateStarted: function() {
  3260.     },
  3261.     onUpdateEnded: function() {
  3262.       // There are still incompatibilities, even after an extension update
  3263.       // check to see if there were newer, compatible versions available, so
  3264.       // we have to prompt.
  3265.       //
  3266.       // PREF_APP_UPDATE_INCOMPATIBLE_MODE controls the mode in which we
  3267.       // handle incompatibilities:
  3268.       // UPDATE_CHECK_NEWVERSION    We count both VersionInfo updates _and_
  3269.       //      NewerVersion updates against the list of incompatible addons
  3270.       //      installed - i.e. if Foo 1.2 is installed and it is incompatible
  3271.       //      with the update, and we find Foo 2.0 which is but which is not
  3272.       //      yet downloaded or installed, then we do NOT prompt because the
  3273.       //      user can download Foo 2.0 when they restart after the update
  3274.       //      during the mismatch checking UI. This is the default, since it
  3275.       //      suppresses most prompt dialogs.
  3276.       // UPDATE_CHECK_COMPATIBILITY    We count only VersionInfo updates
  3277.       //      against the list of incompatible addons installed - i.e. if the
  3278.       //      situation above with Foo 1.2 and available update to 2.0
  3279.       //      applies, we DO show the prompt since a download operation will
  3280.       //      be required after the update. This is not the default and is
  3281.       //      supplied only as a hidden option for those that want it.
  3282.       var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE,
  3283.                          nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  3284.       if ((mode == nsIExtensionManager.UPDATE_CHECK_NEWVERSION
  3285.            && this._addons.length) || !isCompatible(update))
  3286.         showPrompt(update);
  3287.     },
  3288.     onAddonUpdateStarted: function(addon) {
  3289.     },
  3290.     onAddonUpdateEnded: function(addon, status) {
  3291.       const Ci = Components.interfaces;
  3292.       if (status != Ci.nsIAddonUpdateCheckListener.STATUS_UPDATE)
  3293.         return;
  3294.  
  3295.       var reqVersion = addon.targetAppID == TOOLKIT_ID ?
  3296.                        update.platformVersion :
  3297.                        update.extensionVersion;
  3298.       if (!addonIsCompatible(addon, reqVersion))
  3299.         return;
  3300.  
  3301.       for (var i = 0; i < this._addons.length; ++i) {
  3302.         if (this._addons[i] == addon) {
  3303.           this._addons.splice(i, 1);
  3304.           break;
  3305.         }
  3306.       }
  3307.     },
  3308.     /**
  3309.      * See nsISupports.idl
  3310.      */
  3311.     QueryInterface: function(iid) {
  3312.       if (!iid.equals(Components.interfaces.nsIAddonUpdateCheckListener) &&
  3313.           !iid.equals(Components.interfaces.nsISupports))
  3314.         throw Components.results.NS_ERROR_NO_INTERFACE;
  3315.       return this;
  3316.     }
  3317.   };
  3318.  
  3319.   if (!isCompatible(update)) {
  3320.     var em =
  3321.         Components.classes["@mozilla.org/extensions/manager;1"].
  3322.         getService(nsIExtensionManager);
  3323.     var items = em.getIncompatibleItemList("", update.extensionVersion,
  3324.       update.platformVersion, nsIUpdateItem.TYPE_ANY, false, { });
  3325.     var listener = new Listener(items);
  3326.     // See documentation on |mode| above.
  3327.     var mode = getPref("getIntPref", PREF_APP_UPDATE_INCOMPATIBLE_MODE,
  3328.                        nsIExtensionManager.UPDATE_CHECK_NEWVERSION);
  3329.     em.update([], 0, mode, listener);
  3330.   }
  3331.   else
  3332. //@line 3325 "e:\fx19rel\WINNT_5.2_Depend\mozilla\toolkit\mozapps\update\src\nsUpdateService.js.in"
  3333.     showPrompt(update);
  3334. }
  3335.